突变中的 Vuex 动态模块未定义状态
Vuex dynamic module undefined state in mutations
我正在尝试对 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 设置中有语法错误,但我正在画一个空白。
有什么帮助吗?
谢谢!
您应该通过 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.
我正在尝试对 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 设置中有语法错误,但我正在画一个空白。
有什么帮助吗?
谢谢!
您应该通过 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.