【发布时间】:2021-02-19 16:01:29
【问题描述】:
我的目标是提交(调用/调用)我在 Vuex 商店中定义的突变。
store/store.js
export default {
modules: {
app: {
state: {
shouldDoThing: false,
}
mutations: {
setShouldDoThing: (state, doThing) => { state.shouldDoThing = doThing },
}
}
}
}
由于我将 Vuex 附加到我的应用程序,我可以在整个应用程序的各个组件中使用 this.$store.commit 而不会出现问题。
main.js
import Store from 'store/store.js';
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const app = new Vue({
el: '#app-root',
store,
// ...etc
});
例如:
exampleComponent.vue
export default {
created() {
// This works!
this.$store.commit('setShouldDoThing', true);
},
}
现在我想通过 beforeEnter 方法从 vue-router 路由文件中提交一些内容:
exampleRoute.js
import Store from 'store/store.js'
const someRoute = {
path: '/blah',
beforeEnter(to, from, next) {
Store.commit('setShouldDoThing', true);
next();
}
}
但是,当我尝试上述方法时,我得到了错误
TypeError: _state_store__WEBPACK_IMPORTED_MODULE_10__.default.commit is not a function
网上有很多通过导入成功使用 vuex getter 的例子。而且,如果我将console.log() Store 导入,我可以看到我的整个商店结构
modules:
app:
actions: {someAction: ƒ, …}
getters: {isStartingQuery: ƒ}
mutations: {ariaAnnounce: ƒ, …}
state: {…}
__proto__: Object
如何从 vue-router 文件中导入我的 Store 和 commit 突变?
【问题讨论】:
标签: vue.js vuex vue-router