说说 Vuex 的 getters 属性

版权声明:如果喜欢,就点个赞呗 O(∩_∩)O~ https://blog.csdn.net/deniro_li/article/details/89292782

1 应用场景

假设我们在 Vuex 中定义了一个数组:

const store = new Vuex.Store({
    state: {
        list:[1,3,5,7,9,20,30]
    }
  ...
})

业务场景希望过滤出大于 5 的数。马上想到的方法可能的是:在组件的计算属性中进行过滤:

<template>
    <div>
        {{list}}
    </div>
</template>
<script>
    export default {
        name: "index.vue",
        computed: {
            list() {
                return this.$store.state.list.filter(item => item > 5);
            }
        }
  }
</script>

效果:

功能虽然实现了,但如果其它组件也需要过滤后的数据,那么就得把 index.vue 中的计算过滤代码复制出来。如果过滤规则发生变化,还得一一修改这些组件中的计算属性,很难维护。这种场景下,我们就可以使用 getters 属性啦O(∩_∩)O~

2 基础用法

main.js:

const store = new Vuex.Store({
    state: {
        list: [1, 3, 5, 7, 9, 20, 30]
    },
    getters: {
        filteredList: state => {
            return state.list.filter(item => item > 5)
        }
    }
})

index.vue:

<script>
    export default {
        name: "index.vue",
        computed: {
            list() {
                return this.$store.getters.filteredList;
            }
        }
    }
</script>

效果达到了,而且只需要在一处维护过滤规则即可。

3 内部依赖

getter 可以依赖其它已经定义好的 getter。比如我们需要统计过滤后的列表数量,就可以依赖之前定义好的过滤函数。

main.js:

扫描二维码关注公众号,回复: 5891329 查看本文章
const store = new Vuex.Store({
    state: {
        list: [1, 3, 5, 7, 9, 20, 30]
    },
    getters: {
        filteredList: state => {
            return state.list.filter(item => item > 5)
        },
        listCount: (state, getters) => {
            return getters.filteredList.length;
        }
    }
})

index.vue:

<template>

    <div>
        过滤后的列表:{{list}}
        <br>
        列表长度:{{listCount}}
    </div>
</template>

<script>
    export default {
        name: "index.vue",
        computed: {
            list() {
                return this.$store.getters.filteredList;
            },
            listCount() {
                return this.$store.getters.listCount;
            }
        }
    }
</script>

效果:

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/89292782