3

我正在尝试使用 sfc 方法将 v-i18n 实施到我的项目中。我无法让它工作。我不会让你对我的项目感到困惑,这就是为什么在官方 v-i18n sfc 示例中添加 10-15 行代码的原因。

这很简单地说明了我的问题。

对于那些喜欢在 github 上查看这个非常小的问题项目的人

https://github.com/berkansivri/V-i18n-Question

组件1.vue

<template>
    <p>{{$t('lang')}}</p>
</template>

<i18n>
{
  "en":{
    "lang" : "English"
  },
  "es":{
    "lang": "Espanol"
  }
}
</i18n>

应用程序.vue

<template>
  <div id="app">
    <label for="locale">locale</label>
    <select v-model="locale">
      <option>en</option>
      <option>es</option>
    </select>
    <p>message: {{ $t('hello') }}</p>
    <Comp1></Comp1>
  </div>
</template>

<i18n>
{
  "en": {
    "hello": "hello"
  },
  "es": {
    "hello": "hola"
  }
}
</i18n>

<script>
import Comp1 from './components/component1'
export default {
  components:{
    Comp1
  },
  name: 'App',
  data () { return { locale: 'en' } },
  watch: {
    locale (val) {
      this.$i18n.locale = val
    }
  }
}
</script>

因此,<i18n>多个组件中的多个标签。我刚刚从 App.vue 修改了 $i18n.locale,但它没有$t('lang')在 Component1 上触发相关的 i18n 函数,只是$t('hello')对其自身进行了修改。我怎样才能让它工作?

4

2 回答 2

0

这是单文件组件的预期行为。如果要更改所有组件的所有语言环境,可以使用:

locale (val) {
  // this.$i18n.locale = val
  this.$root.$i18n.locale = val
}

看到这个问题

于 2019-06-02T16:04:34.873 回答
0

使用 vue devtools 你会发现单个文件组件中 $i18n 的消息彼此不同,因此它们是不同的对象。

你需要做的是:

i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from '@/lang'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'cn',
  fallbackLocale: 'en',
  messages
})

export default i18n

应用程序.vue

import i18n from "./i18n.js"
i18n.locale = "en"
于 2019-05-31T08:18:34.783 回答