我的目标是提交(调用/调用)我在 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
如何导入我的 Store,然后从 vue-router 文件中提交
更改?
最佳答案
我已经在谷歌上搜索了很长一段时间,没有找到针对这个特定案例或问题的 stackoverflow 答案或 vue 论坛答案,所以下面是我测试过并适用于我的案例的解决方案。
无论出于何种原因,我都无法触发提交
。但是,我可以简单地直接调用突变,然后此更改会反射(reflect)在其他组件中(例如,未导入“不同”存储)。
someRoute.js
import Store from 'store/store.js'
const someRoute = {
path: '/blah',
beforeEnter(to, from, next) {
Store.modules.app.mutations.setShouldDoThing(Store.modules.app.state, true);
next();
}
}
后来,在某些组件中:
someComponent.vue
export default {
beforeMount() {
console.log(this.$store.state.app.shouldDoThing);
// true
}
}
关于vue.js - 如何从导入 "store"的 vue-router 路由内部提交 vuex 存储突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64722761/