2

So lets say I want to add this {{ $t('index-p1') }} inside the value of title.

items: [
        {
          icon: 'mdi-apps',
          title: 'Welcome',
          to: '/'
        },

I am using this for i18n and the data that the {{ $t('index-p1') }} contains is stored in a JSON file. It works just fine if I use it in a Vue template file, but not in data, I don't remember how to do this part.

Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46

2 Answers2

1

items should be defined as computed property, and access $t using this :

computed:{
   items(){
     return [
        {
          icon: 'mdi-apps',
          title: this.$t('welcome'),
          to: '/'
        }
     ]
   }
}
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
1

You can use computed property and call it with this.$t:

const messages = {
  en: {
    message: {
      hello: 'hello world'
    }
  },
  fr: {
    message: {
      hello: 'bonjour'
    }
  }
}

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

new Vue({
  i18n,
  computed: {
    text() { return this.$t("message.hello")}
  },
  methods: {
    setLang(lang) {
      i18n.locale = lang
    }
  }
}).$mount('#demo')
items: [
        {
          icon: 'mdi-apps',
          title: 'Welcome',
          to: '/'
        },
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-i18n/8.15.5/vue-i18n.min.js"></script>
<div id="demo">
  <button @click="setLang('fr')">fr</button>
  <button @click="setLang('en')">en</button>
  <p>{{ $t("message.hello") }}</p>
  {{ text }}
</div>
Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46