本文主要是介绍Vuex中getters的使用方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Vuex中getters的使用方法
前提脚手架搭好Vuex,项目内store文件夹下的index.js实例代码
export default createStore({state: {todos: [{ id: 1, text: '...1', done: true },{ id: 2, text: '...2', done: false },{ id: 3, text: '...3', done: true }]},getters: {// 基础用法,参数statedoneTodos: state => {return state.todos.filter(todo => todo.done)},// 基础用法,参数gettersdoneTodosCount: (state, getters) => {return getters.doneTodos.length},// 方法传参getTodosById: state => id => {return state.todos.find(todo => todo.id === id)}}
})
基础用法
用法①直接访问
打印出来的效果↑
<template><div>{{ fn1 }}</div>
</template>
<script>import { mapState } from 'vuex'export default {...computed:{fn1 () {// 直接操作store数据,不使用Vuex的getters属性return this.$store.state.todos.filter(todo => todo.done)}}}
</script>
用法②通过属性访问,参数state(效果同上)
getters:{doneTodos: state => {return state.todos.filter(todo => todo.done)}
}
<template><div>{{ fn2 }}</div>
</template>
<script>import { mapState } from 'vuex'export default {...computed:{fn2 () {// 调用Vuex的getters属性的方法,其相当于store的计算属性// 逻辑操作写在getters里面return this.$store.getters.doneTodos}}}
</script>
用法③方法参数getters
打印出来的效果
getters:{doneTodos: state => {return state.todos.filter(todo => todo.done)},donTodosCount: (state, getters) => {// 参数getters,调用上面的方法return getters.doneTodos.length}
}
<template><div>{{ fn3 }}</div>
</template>
<script>import { mapState } from 'vuex'export default {...computed:{fn3 () {return this.$store.getters.doneTodosCount}}}
</script>
用法④通过方法访问
getters: {getTodoById: state => id => {return state.todos.find(todo => todo.id === id)}
}
<template><div>{{ fn4 }}</div>
</template>
<script>import { mapState } from 'vuex'export default {...computed:{fn4 () {// 参数可以绑定(data)局部数据return this.$store.getters.getTodoById(3)}}}
</script>
用法④辅助函数mapGetters
<template><div>{{ doneTodos}}<br><br>{{ doneTodosCount }}<br><br>{{ getTodoById(3) }}</div>
</template>
// 写法1
<script>import { mapState, mapGetters } from 'vuex'export default {...computed:{// 方法属性同名...mapGetters(['doneTodos','doneTodosCount','getTodoById'])}}
</script>
// 写法2
<script>import { mapState, mapGetters } from 'vuex'export default {...computed:{// 可修改getters属性名字,注意这里使用{}...mapGetters({doneTodos: 'doneTodos',doneTodosCount: 'doneTodosCount',getTodoById: 'getTodoById'})}}
</script>
这篇关于Vuex中getters的使用方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!