Home > Software engineering >  How do I call an object inside the Vue data as the value of an item?
How do I call an object inside the Vue data as the value of an item?

Time:09-29

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.

CodePudding user response:

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

computed:{
   items(){
     return [
        {
          icon: 'mdi-apps',
          title: this.$t('welcome'),
          to: '/'
        }
     ]
   }
}

CodePudding user response:

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>

  • Related