【问题标题】:Reactive getter in vuex?vuex中的反应式吸气剂?
【发布时间】:2017-10-11 20:23:50
【问题描述】:

我在 vuex 中有 getter,它从列表中返回项目

const store = new Vuex.Store({
    state: { arr: {
        1: {name: 'one', attr: true},
        2: {name: 'two', attr: false} 
    },
    mutations: {
        setArrItemName(state, id, name) {
            Vue.set(state.arr, id, name);
        }
    },
    getters: {
        arrItemById(state, getters) => (id) => {
            const item = state.arr[id];
            if(item) return item;
            return {
                 name: 'default', attr: true
            };
        }
    }
})

如果我在模板中输出它

{{ $store.state.arr[1]['name'] }}

当另一部分调用时它会正常更新

this.$store.commit('setArrItemName', 1, 'new name');

但如果模板包含

{{ $store.getters.arrItemById(1).name }}

那就不更新了

问题:这个getter用在不同的地方,我不想重复这段代码

<template v-if='$store.state.arr[id]'>
    {{ $store.state.arr[id].name }}
</template>
    Default
<template v-else>
</template>

如果某天“默认”发生变化,或者default 对象的任何其他属性,那么它应该在不同的地方更新。

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    尝试使用计算属性来访问您的 getter。首先,从Vuex导入mapGetters函数:

    import {mapGetters} from 'vuex';
    

    然后,为所需的 getter 添加计算属性,如下所示:

    computed: {
        ...mapGetters({
            getterName: 'your-getter-name-in-store'
        })
    } 
    

    我们在使用 mapGetters 助手时使用了一个扩展操作符(...);你可以阅读更多关于为什么here

    然后,在您的模板中,使用{{ getterName }}

    这也解决了您的代码重复问题,因为您无需在任何地方使用this.$store.getters

    【讨论】:

    • 如何传递 id ? getter 返回一个函数,说明为什么 vuex 不能应用响应式,而是使用直接状态。 Vuex 对状态应用响应式,但不是函数的获取器。
    • @Tobino Sry 我不明白你在问什么。 ://
    • 我没有很好地解释,并且输入错误......我认为,当前的问题是获取带有 ID 的商店子集。你的anwser,不要映射Id。这更像是一个组件设计问题而不是 Store 问题。
    • @Tobino 这是你说的解决方案是正确的stackoverflow.com/a/44984484/7814783 吗?
    • 我已经尝试做一个新的实现,在 Store 中使用业务逻辑并使用计算函数获取反应数据。 stackoverflow.com/a/45265387/2054427我提供了一个jsfiddle以获得更多解释。
    【解决方案2】:

    你不能对不纯的 getter 做出反应。 您可以在本地创建计算属性。

    来源:https://github.com/vuejs/vuex/issues/145#issuecomment-230488443

    我做了一些研究,你可以使用带有 getter 的计算函数:

      computed: {
        arr() {
                return this.$store.getters.arrItemById(this.id);
          }
      },
    

    这是一个jsfiddle 示例。

    【讨论】:

      【解决方案3】:

      我不知道这个错字是否只是在问题中,还是在您的程序中......

      从上方

      const store = new Vuex.Store({
          state: { arr: {
              1: {name: 'one', attr: true},
              2: {name: 'two', attr: false} 
          },
          mutations: {
             ...
      

      应该是

      const store = new Vuex.Store({
          state: { arr: {
              1: {name: 'one', attr: true},
              2: {name: 'two', attr: false} 
            } // missing this closing brace on object arr
          },
          mutations: {
             ...
      

      这或许可以解释 getter 问题。

      【讨论】:

        猜你喜欢
        • 2021-06-01
        • 2017-10-18
        • 1970-01-01
        • 2019-11-17
        • 2022-01-20
        • 2018-11-16
        • 2018-10-13
        • 2018-04-05
        • 2019-10-05
        相关资源
        最近更新 更多