首页 > 解决方案 > 在创建它的同一模块中使用 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未定义。

标签: vue.jsvuex

解决方案


this不存在于对象的上下文中,仅适用于构造函数或类。

我在这里看到两个问题。

首先,你不能引用对象本身,因为它还没有被定义。在声明具有公共属性的对象(在本例中为 getter 函数)之前,您必须创建一个局部变量。

其次,更重要的是,我不确定它是否有助于访问 getter (Reducer) 函数,因为它不知道状态,当处理突变时,底层 Vuex 库将状态作为第一个参数传递给它(行动)。

Vuex 基于 Redux 模式,Action -> Reducer -> Store,我建议阅读一下关于 Redux 工作原理的快速介绍,因为它将帮助您更好地理解 Vuex 内部的操作流程。


推荐阅读