Can Tomris
Can Tomris

Reputation: 31

Using i18n-nuxt $t in Vuex store

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.

Upvotes: 3

Views: 6286

Answers (2)

Andrea
Andrea

Reputation: 151

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.

Upvotes: 3

Dacxj0
Dacxj0

Reputation: 161

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.

Upvotes: 1

Related Questions