getter
getter其实就是state的计算属性,就像组件里面属性的计算属性
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
通过属性访问
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:0
},
getters:{
deubleCount:(state)=>state.count+3
},
// mutations: {
// },
// actions: {
// },
// modules: {
// }
})
<template>
<div class="home">
<div>{{count}}</div>
<div>{{countAlias}}</div>
<div>{{countPlusLocalState}}</div>
<div>{{$store.getters.deubleCount}}</div>
<button @click="$store.state.count ++">click</button>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
data () {
return {
// count: 100
}
},
computed: {
...mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this
}
})
}
}
</script>
通过方法访问
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。 ( 注 意 , g e t t e r 在 通 过 方 法 访 问 时 , 每 次 都 会 去 进 行 调 用 , 而 不 会 缓 存 结 果 。 ) \color{red}{(注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。)} (注意,getter在通过方法访问时,每次都会去进行调用,而不会缓存结果。)
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
mapGetters辅助函数
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果需要修改名称就使用对象的方式
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})