首页 > 解决方案 > 如何访问兄弟 Vuex 状态属性和 getter

问题描述

我有数据要在不同的场景中填充和更新。在这些情况下,我需要填充“href”和“href2”每当我尝试按照下面的代码进行填充时,我得到

  1. 未捕获的类型错误:无法读取未定义的属性“getters”-(试图从 getters 中引用)

  2. 同样,当从兄弟 Vuex 状态数据引用时Uncaught TypeError: Cannot read property 'locationId' of undefined

这是来自我的 Vuex 商店的示例片段。

注意:我试图做的这个参考/调用是在我的 Vuex 商店中。

我需要帮助了解如何在 Vuex Store 中正确引用这些数据。先感谢您。

export default new Vuex.Store({
  state: {
    defaultLocationId: "/...",
    updatedLocationFromAction: "",
    navData: [
      ...,
      {
        title: "Location",
        icon: "fa fa-map-marker",
        href: "/locations/" + this.defaultLocationId,
        href2: "/locations/" + this.getters.anotherLocation,
      },
      ...,
    ],
  },
  getters: {
    anotherLocation(state) {
      return state.updatedLocationFromAction;
    },
  },
});

标签: javascriptvue.jsvuex

解决方案


如果要更改状态,则需要使用突变并检索使用 getter。这是 codepen 中 vuex 的一个很好的工作示例。一探究竟:

https://codepen.io/brokyo/pen/rGRZxe

mutations: {
    UPDATE_DATA (state, payload) { // your location change
      state.person = payload
    }
  }

推荐阅读