【问题标题】:Vuex dynamic module undefined state in mutationsVuex动态模块未定义状态突变
【发布时间】:2019-12-11 14:52:22
【问题描述】:

我正在尝试对 Vue 插件进行故障排除,以使其与 Nuxt 一起使用。它使用动态存储模块,并且由于某种原因,它使用的所有突变都会出现state is undefined 错误。

它的基本原理是:

index.js

import mixin from './src/mixin'
import store from './src/store'

export default {
    install: function(Vue, options = {}) {
        options = {
            store: null,
            ...options
        }

        options.store.registerModule('shopify', store)

        // define mixin
        Vue.mixin(mixin)
    }
}

然后store.js文件基本上是这样的:

export default {
    state: {
        product: [],
    },
    mutations: {
        UPDATE_CACHED_RESULT(state, { id, data }) {
            // This is the line that throws a state error
            state.product[id] = data
        }
    },
    actions: {
    }
}

我假设我现在在 Nuxt 设置中的语法错误,但我正在画一个空白。

有什么帮助吗?

谢谢!

【问题讨论】:

    标签: state vuex store nuxt.js


    【解决方案1】:

    您应该通过context 访问您的store 属性。如 Nuxt.js 文档中所述,如果您导出函数,则 context 将作为该函数的第一个参数提供。因此,您可以访问应用程序的实际 store,并对商店进行一些更改(在您的案例注册模块中)。

    export default (context, inject) => {
      context.store.registerModule("foo", {
        state: {
          id: 1
        },
        mutations: {
          bar(state) {
            state.id = 2;
          }
        }
      });
    }
    

    然后在nuxt.config.js注册那个插件:

    plugins: [
      "~/plugins/name-of-your-plugin"
    ]
    

    P.S.:这个模块注册在我的应用程序中运行良好,但我不确定mixin,也许添加这些代码行会有所帮助:

    import Vue from "vue";
    import mixin from "./src/mixin";
    
    Vue.mixin(mixin);
    
    // then export aforementioned function.
    

    Reference.

    【讨论】:

    • 嗨,我有一个类似的问题我的问题是我的自定义插件中的install 只被调用一次。因此,该模块已注册,然后在后续加载该模块不存在
    猜你喜欢
    • 2018-09-22
    • 2021-02-01
    • 2020-12-18
    • 2019-08-17
    • 2018-08-09
    • 2018-05-16
    • 2019-08-25
    • 2019-10-12
    • 2018-05-13
    相关资源
    最近更新 更多