使用Vuex经典模式Nuxt应用

问题描述 投票:0回答:1

我重写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有一些其他的方法,它可是我真的想坚持上面的代码。 Unfortuenally我不能叫突变从我的组件:

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;

现在的错误是

遗漏的类型错误:store.registerModule不是一个函数

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

vuejs2 vuex nuxt.js ssr nuxt
1个回答
3
投票

您需要使用经典模式。

经典(不推荐):存储/ index.js返回到创建存储实例的方法

因此,它应该是这样的,没有vuex使用,在Vue公司的进口。它必须是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
}
© www.soinside.com 2019 - 2024. All rights reserved.