3

My problem is kinda specific. I'm using Vuex and Nuxt for this project. For the dependency we use i18n-nuxt but somehow I cannot use $t('some.translation') in the $store while in the components it works just fine. I tried every possible combinations I can imagine but still the result leads me to the same error.

ReferenceError $t is not defined or Cannot read the property of i18n

So in this case I could use some help either to solve this problem or it would be perfect if someone shows me the way how to use i18n as a filter. (Which I think is the only way around.)

For example this code block is from the $store.state

  sortMethods: [
{ id: 'airline', name: this.i18n.$t('Airline'), asc: 'A', desc: 'Z', defaultDirection: 'asc' },

You can imagine I cannot translate them where they are.

Can Tomris
  • 31
  • 1
  • 6

2 Answers2

3

It's possible to use t in mutations and actions with this.$i18n.t. Ex.:

export const mutations = {
  foo() {
    console.log(this.$i18n.t("bar"));
  }
}

However I haven't found a way to use it in the state or getters because they don't have access to this.

Andrea
  • 141
  • 1
  • 8
  • `this.$i18n.te` works too! You just need to be careful and remove the damn `$` in front of all of those! – kissu Aug 04 '21 at 14:36
1

i18n module is not injected in the store context by default , and the “this” keyword cannot access to the module too.

Is not a better approach to save a key from the translation file as a value in the store or even use the id of the object as the same translation key, and then in the component use the $t function to translate?

Like the following

store.js

const state = {
   sortMethods: [
        {
           id: “airline”, 
           key_name: “airline”
        }
   ]
}

And then in the select tag from your component.vue:

<option v-for=“method in $store.state.sortMethods” :key=“method.id”> {{$t(method.key_name)}}</option>

This will give you a translated list from the store. No need to translate directly.

You can use an id, a key, even the name, always that the translation key is the same in your lang file.

Dacxj0
  • 141
  • 3
  • 9