在Nuxt应用程序中使用Vuex经典模式

时间:2019-02-06 01:55:40

标签: vuejs2 vuex nuxt.js ssr nuxt

我将Vue应用程序重写为Nuxt架构,因为我们需要SSR。但是我不想重写Vuex存储文件,该文件是:

import Vue from "vue";
import Vuex from "vuex";
import vuexI18n from "vuex-i18n/dist/vuex-i18n.umd.js";
import toEnglish from "../translations/toEnglish";
import toSpanish from "./../translations/toSpanish";
import toGerman from "./../translations/toGerman";
import toRussian from "./../translations/toRussian";

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        currentLanguage: ''
    },
    mutations: {
        changeLang: (state, response) => {
            if(response) {
                state.currentLanguage = response;
                Vue.i18n.set(response);
                console.log(response);
            }
        }
    }
});

Vue.use(vuexI18n.plugin, store);
Vue.i18n.add("en", toEnglish);
Vue.i18n.add("es", toSpanish);
Vue.i18n.add("de", toGerman);
Vue.i18n.add("ru", toRussian);

export default store;

我知道Nuxt还有其他方法,但是我真的想坚持使用上面的代码。不幸的是,我无法通过以下方式从组件中调用突变:

this.$store.commit('changeLang', lang)

它在控制台中打印错误:

  

[vuex]未知突变类型:changeLang

我也这样尝试过

this.$store.commit('store/changeLang', lang)

但是错误是相同的。如何解决?我需要重写此vuex文件才能使其正常工作吗?


我遵循@Aldarund提示,并将上面的代码更改为:

import Vue from "vue";
import Vuex from "vuex";
import vuexI18n from "vuex-i18n/dist/vuex-i18n.umd.js";
import toEnglish from "../translations/toEnglish";
import toSpanish from "./../translations/toSpanish";
import toGerman from "./../translations/toGerman";
import toRussian from "./../translations/toRussian";

const store = () => {
    return new Vuex.Store({
        state: () => ({
            currentLanguage: ''
        }),
        mutations: {
            changeLang: (state, response) => {
                if (response) {
                    state.currentLanguage = response;
                    Vue.i18n.set(response);
                    console.log(response);
                }
            }
        }
    })
};

Vue.use(vuexI18n.plugin, store);
Vue.i18n.add("en", toEnglish);
Vue.i18n.add("es", toSpanish);
Vue.i18n.add("de", toGerman);
Vue.i18n.add("ru", toRussian);

export default store;

现在错误是

  

未捕获的TypeError:store.registerModule不是函数

可能是因为Vue.use(vuexI18n.plugin, store);

1 个答案:

答案 0 :(得分:2)

您需要使用经典模式。

  

经典(不建议使用):store / index.js返回创建   商店实例

因此,在导入Vue时应该看起来像这样,不使用vuex。而且它必须是crestr存储的函数,而不是普通的vuex对象

import Vuex from 'vuex'

const createStore = () => {
  return new Vuex.Store({
    state: () => ({
      counter: 0
    }),
    mutations: {
      increment (state) {
        state.counter++
      }
    }
  })
}

export default createStore

文档https://nuxtjs.org/guide/vuex-store/#classic-mode

关于插件,例如vyexi18,您需要将该代码移动到插件文件中,并从上下文https://nuxtjs.org/guide/plugins/

中创建存储对象
export default ({ store }) => {
  Your vuex18initcode
}
相关问题