【问题标题】:How to access a sibling Vuex state property and getters如何访问兄弟 Vuex 状态属性和 getter
【发布时间】:2021-06-01 08:43:18
【问题描述】:

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

  1. Uncaught TypeError: Cannot read property 'getters' of undefined - (试图从 getter 中引用)

  2. 从兄弟 Vuex 状态数据引用时也是如此未捕获的类型错误:无法读取未定义的属性 'locationId'

这是来自我的 Vuex 商店的示例 sn-p。

注意:我试图做的这个参考/调用是在我的 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;
    },
  },
});

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    Vuex 的 getter/mutations/actions 是 pure 函数 - 没有像 Vue 组件中那样的 this ,所有信息仅通过参数传递。您应该从状态中删除 hrefhref2 并将它们转换为 getter 函数。

    【讨论】:

      【解决方案2】:

      如果你想改变状态,你需要使用突变和检索使用 getter。这是 codepen 中 vuex 的一个很好的工作示例。看看吧:

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

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

      【讨论】:

        猜你喜欢
        • 2021-09-23
        • 1970-01-01
        • 2021-11-11
        • 2021-03-28
        • 2019-11-17
        • 1970-01-01
        • 1970-01-01
        • 2020-01-31
        • 2021-09-15
        相关资源
        最近更新 更多