首页 > 解决方案 > Vuex 从 getter 访问 this.$store

问题描述

我正在尝试从 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.jsvuejs2vuexvuex-modules

解决方案


因为 getter不应该提交突变,也许你可以设置一个观察者,所以当 getter 调用更新时,你可以提交,或者如果你真的这样做,你可以导入存储并从导入的存储调用提交。

import store from "../index";

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

  //Store imported
  store .commit('showInfoDialog', { message: 'test', type: 'error'});

  return someData;
}

推荐阅读