vue.js - 在创建它的同一模块中使用 getter
问题描述
state's property
是否可以使用getter
在同一模块中创建的初始化?像这样的东西:
export const gamesModule = {
state: {
games: [],
selectedGameID: null,
playerOnTurnID: this.getters.getSelectedGame.playerData[0]
},
getters: {
getGames: state => state.games,
getselectedGameID: state => state.selectedGameID,
getSelectedGame: state => getSelectedGameById(state.games, state.selectedGameID),
},
mutations: {
SET_GAMES (state, game) {
state.games.push(game);
},
SET_SELECTED_GAME_ID (state, id) {
state.selectedGameID = id;
},
SET_PLAYER_ON_TURN_ID (state, playerID) {
state.playerOnTurnID = playerID;
}
},
actions: {
async createGame({ commit }) {
try {
const { data } = await gameService.createGame();
commit('SET_GAMES', data);
} catch (error) {
console.warn('Error creating new game: ', error);
}
},
setSelectedGameID({ commit }, id) {
commit('SET_SELECTED_GAME_ID', id);
},
};
像这样写,它不起作用,因为getters
未定义。
解决方案
this
不存在于对象的上下文中,仅适用于构造函数或类。
我在这里看到两个问题。
首先,你不能引用对象本身,因为它还没有被定义。在声明具有公共属性的对象(在本例中为 getter 函数)之前,您必须创建一个局部变量。
其次,更重要的是,我不确定它是否有助于访问 getter (Reducer) 函数,因为它不知道状态,当处理突变时,底层 Vuex 库将状态作为第一个参数传递给它(行动)。
Vuex 基于 Redux 模式,Action -> Reducer -> Store,我建议阅读一下关于 Redux 工作原理的快速介绍,因为它将帮助您更好地理解 Vuex 内部的操作流程。
推荐阅读
- c++ - Why move on std::map is failing to move a element from one map to other
- node.js - React App 安装后编译失败
- elasticsearch - 线程“Thread-21”中的异常 java.lang.NoSuchFieldError: FAIL_ON_SYMBOL_HASH_OVERFLOW
- c++ - 将二维数组作为类构造函数的参数输入时如何将其作为参考
- sql - 避免重复来自 2 个左连接表的聚合列值
- python - 如何将 celery 集成到 flask + redis 中?
- apache-kafka - 保留.bytes 是否定义了非活动段的最大大小?
- java - jhipster/spring keycloak 集成 - 设置自定义 redirect_uri
- android - 在 AutocompleteSupportFragment 中只想显示机场建议?
- c# - 将 C# UdpClient 连接到代理