4

I am trying to implement v-i18n to my project with sfc method. I couldn't make it work. I will not make you confuse with my project, that's why just modified with adding 10-15 lines of code to official v-i18n sfc example.

This is very simply shows my question.

For those who prefer check this very tiny question project on github

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

Component1.vue

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

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

App.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>

So, multiple <i18n>tag in multiple components. I just modified $i18n.locale from App.vue but it did not fire related i18n function $t('lang') on Component1, just modifies $t('hello') on itself. How can I make it work?

berkan
  • 722
  • 1
  • 7
  • 23
  • 1
    Apparently you rely on [this guide](http://kazupon.github.io/vue-i18n/guide/sfc.html#basic-usage). So, did you install [vue-i18n-loader](https://github.com/kazupon/vue-i18n-loader) and configure vue.config.js for it? – vahdet May 14 '19 at 07:36
  • @vahdet Yes, you can check my github repo. I did not copy everything to make question unreadable, even it is very tiny. – berkan May 14 '19 at 07:38

2 Answers2

1

using vue devtools u will find out that messages of $i18n in single file component is different from each other, so they are different objects.

u need to do is:

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

App.vue

import i18n from "./i18n.js"
i18n.locale = "en"
Caesar You
  • 11
  • 2
0

This is intended behavior of Single file components. If you want to change all locales of all components you can use:

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

See this issue.

User 28
  • 4,863
  • 1
  • 20
  • 35