How to get global variable in store mutation

2019-07-26 02:20发布

I am getting error about using vue-i18n dependance.

How should i get the const i18n from main.js to root.js (store)

I am using

  • Vuejs 2.X
  • Vue-i18n latest
  • Vuex For Vuejs 2.X

In main.js (vue-cli)

Vue.use(VueI18n)

const i18n = new VueI18n({
    locale: 'en',
    messages: {
        en: {
            message: en
        },
        cn: {
            message: cn
        }
    }
})

new Vue({
    store,
    el: '#app',
    i18n,
    router,
    template: '<App/>',
    components: { App }
})

In root.js (store)

export const mutations = {
    [types.SET_LANGUAGE] (state, data) {
        console.log(i18n.locale) // 'i18n' is not defined
        localStorage.setItem('language', data)
    },
}

1条回答
何必那么认真
2楼-- · 2019-07-26 02:36

As mentioned in my comment, put it in it's own file, eg i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n' // or whatever the module is called

Vue.use(VueI18n) // you don't need this in main.js

export default new VueI18n({
  locale: 'en',
  messages: {
    en: {
      message: en
    },
    cn: {
      message: cn
    }
  }
})

Then, in main.js and root.js...

import i18n from './i18n'
查看更多
登录 后发表回答