Vuex学习总结 - Getters(4)
4.Vuex核心概念
4.2 Getters
Vuex实例的getters
相当于计算属性,getters
的结果根据其依赖关系进行缓存,并且在其依赖发生更改时才重新计算。
getters
将Vuex实例的state
作为第一个参数。
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
todos: [
{id: 1, text: 'study', done: true},
{id: 2, text: 'housework', done: false},
],
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
},
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
},
},
})
在组件中直接使用。
{{this.$store.getters.doneTodos[0].text}}
<br/>
{{this.$store.getters.doneTodosCount}}
<br/>
{{this.$store.getters.getTodoById(2).text}}
通过mapGetters
使用。
<template>
<div class="about">
<h1>This is an about page</h1>
{{$store.state.count}}
<br/>
{{doneTodos[0].text}}
<br/>
{{doneTodosCount}}
<br/>
{{getTodoById(2).text}}
</div>
</template>
<script>
import {mapGetters} from 'vuex'
export default {
computed: mapGetters(['doneTodos','doneTodosCount','getTodoById'])
}
</script>