vue.js - 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 中未定义?
解决方案
因为 getter不应该提交突变,也许你可以设置一个观察者,所以当 getter 调用更新时,你可以提交,或者如果你真的想这样做,你可以导入存储并从导入的存储调用提交。
import store from "../index";
const getters = {
showInfoDialogWithCalculatedData(state) {
//... some actions
//Store imported
store .commit('showInfoDialog', { message: 'test', type: 'error'});
return someData;
}
推荐阅读
- gatling - Gatling 在模拟开始前写入 .csv 文件
- python - Python 中的网络爬虫:查找标签值
- php - Woocommerce 中特定运输类别、最低金额和特定国家/地区的免费送货购物车消息
- c++ - 分配 x 指向 y 指向的位置会导致任何内存泄漏吗?
- django - 视图中的 Django 内联表单集字段必需/非必需设置
- javascript - 如何缩短此 java 脚本代码长度并添加动画?
- android-jetpack-compose - 撰写 w Google 地图:协程中的 mapView.getMapAsync 与 mapView.awaitMap
- javascript - 如何使用 VS Code 中的 Tab 使自动完成功能正常工作?
- django - Django:将列、字段从子模型移动到父模型?
- java - 如何在 Java 中解析其元素均已命名的 JSON 列表?