Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make prototype accessible in vuex

In my app.js file I build this so I can use translation in vue:

Vue.prototype.trans = string => _.get(window.i18n, string);

This is working great in my vue files:

{{ trans('translation.name') }}

The problem is that I'm using vuex and I need to translate some things in a module:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default {
    namespaced: true,

    state: {
        page: 1,
        criterias: [
            {
                name: this.trans('translation.name'),
                filter: "life",
                active: false
            }
     }
 }

But here this.trans('translation.name') is not working. How could I get this to work?

like image 291
Jamie Avatar asked Jan 21 '19 15:01

Jamie


1 Answers

I would call mutating Vuex prototype as a bad practice and in this case, it's really not necessary.

Simply create a file called localization.js and instantiate the i18n plugin in that file. Plus export a named function to return the same i18n instance.

// localization.js

const i18n = new VueI18n({ ... });

export const getLocalization = () => i18n;

export default i18n;

Then in your Vuex module import the getLocalization function and execute it to get the same i18n instance and do translations using it.

// vuex-module.js

import Vue from 'vue';
import Vuex from 'vuex';
import { getLocalization } from './localization';

Vue.use(Vuex);

const i18n = getLocalization();

export default {
  state: {
    criteria: i18n('translation.name'),
  },
}

like image 103
Fatih Acet Avatar answered Oct 11 '22 04:10

Fatih Acet