【问题标题】:Vuex access this.$store from gettersVuex 从 getter 访问 this.$store
【发布时间】:2021-07-06 03:55:24
【问题描述】:

我正在尝试从 getters 部分访问 this.$store.commit,我看到未定义的错误属性“$store”,我能够从突变访问 this.$store,那么为什么不从 getters 访问呢?

我的 store.js 文件

import Vue from 'vue';
import Vuex from 'vuex';
import order from './modules/order/order'
import dialogList from './modules/dialog/dialogList'

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: { },
    getters: {

    },
    modules: {
        order,
        dialogList
    }
});

我的 order.js 文件从 dialogList 调用突变

const state = {
    order: {
       ...
    }
}

const getters = {
    showInfoDialogWithCalculatedData(state) {
    //... some actions

    //here this.$store is undefined
    this.$store.commit('showInfoDialog', { message: 'test', type: 'error'});
    
    return someData;
    }
}

const mutations = {
    showInfoDialogWithCalculatedData(state) {
    //... some actions

    //here this.$store is defined
    this.$store.commit('showInfoDialog', { message: 'test', type: 'error'});
   
    }
}

export default {
    state,
    getters,
}

为什么 this.$store 在 getter 中未定义?

【问题讨论】:

    标签: vue.js vuejs2 vuex vuex-modules


    【解决方案1】:

    因为 getter 不应该提交突变,也许您可​​以设置一个 watcher,所以当 getter 调用更新时,您可以提交或者如果您真的想要这样做可以导入 store 并从导入的 store 中调用 commit。

    import store from "../index";
    
    const getters = {
      showInfoDialogWithCalculatedData(state) {
      //... some actions
    
      //Store imported
      store .commit('showInfoDialog', { message: 'test', type: 'error'});
    
      return someData;
    }
    

    【讨论】:

    • mathieu 您的回答“因为吸气剂不应该提交突变”表明我在重构过程中卡住了:D 非常感谢!
    猜你喜欢
    • 2023-03-18
    • 2019-04-05
    • 2020-05-14
    • 2021-07-26
    • 2019-04-11
    • 1970-01-01
    • 2019-12-29
    • 2017-06-29
    • 1970-01-01
    相关资源
    最近更新 更多