How to use $t from vue-i18n inside Vuex store to initialize static strings

2.5k views Asked by At

In my vuex store module I have provinceData to supply as datasource for Vuetify dropdown selection box.

provinceData:  [
            {value:"AB", text: "Alberta"},
            {value:"BC", text: "British Columbia"},
            ...
        ],

I can import i18n from '../plugins/i18n' and confirm in console output that i18n.t('province.BC') return me proper text from resource files

i18n.t('province.BC') British Columbia
click onLanguageChange fr
i18n.t('province.BC') British Columbia (Fr)

But how I can insert these translations into datasource?

provinceData:  [
            {value:"AB", text: ???i18n.t('province.AB')??? },
            {value:"BC", text: ???i18n.t('province.BC')??? },
            ...
        ]

Now I realized what mistake I did by wrapping i18n.t('province.AB') into back ticks. Here is corrected version which render english only messages:

provinceData:  [
            {value:"AB", text: i18n.t('province.AB') },
            {value:"BC", text: i18n.t('province.BC') },
            ...
        ]

Moreover, will it be reinitialized if I switch the current locale?

PS. When getter for this datasource is hit I can see that message retrieved according to current locale. But dropdown box izn't reloaded. That's the problem

Following getter print correct translation every time it called:

provinceData: (state) => {
            console.log("i18n.t('province.BC')",i18n.t('province.BC'));
            return state.provinceData;
        },
1

There are 1 answers

0
AlexeiP On

Because the provinceData inside the store it can't be modified by anything but mutators. So I decided to create this array right in the getter and it turns out to be quite fast.

provinceData: ( state ) =>
        {
            const provinceData = [ "AB", "BC", "MB", "NB", "NF", "NT", "NS", "NU", "ON", "PE", "QC", "SK", "YT" ];
            let provinces = [];

            provinceData.forEach( (province) => {
                provinces.push
                ({
                    value : province,
                    text  : i18n.t( 'province.'+province )
                })
            })

            return provinces;
        }