【问题标题】:How do I commit a vuex store mutation from inside a vue-router route that imports "store"?如何从导入“存储”的 vue-router 路由内部提交 vuex 存储突变?
【发布时间】: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 而不会出现问题。

ma​​in.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


    【解决方案1】:

    我已经在谷歌上搜索了很长时间,但没有找到针对此特定案例或问题的 stackoverflow 答案或 vue 论坛答案,因此以下是我测试并适用于我的案例的解决方案。

    无论出于何种原因,我都无法触发commit。但是,我可以直接调用突变,然后此更改会反映在其他组件中(例如,未导入“不同”存储)。

    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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 1970-01-01
      • 2019-08-26
      • 2018-05-25
      • 2021-12-12
      • 2019-09-09
      • 2019-02-20
      • 1970-01-01
      • 2021-08-10
      相关资源
      最近更新 更多