vuex的Getters特性(store的计算属性,多组件复用)
- getters可以对state进行计算操作,它就是store的计算属性
- 虽然在组件内也可以做计算属性,但是getters可以在多组件之间复用
- 如果一个状态只在一个组件内使用,是可以不用getters
getters从表面是获得的意思,可以把他看作在获取数据之前进行的一种再编辑,相当于对数据的一个过滤和加工。可以把它看作store.js
的计算属性。
getters基本用法
比如我们现在要对store.js
文件中的count进行一个计算属性的操作,就是在它输出前,给它加上100.
我们首先要在store.js
里用const声明我们的getters属性。
// 3、getters计算过滤操作
const getters = {
// count: (state) => {
// state.count += 100
// }
count (state) {
const gettersCount = state.count += 100
return gettersCount
}
}
其中module模块组中要加上getters
// module模块组
const moduleA = {
state,
mutations,
getters
}
export default new Vuex.Store({
modules: { a: moduleA }
})
在store.js
里的配置算是完成了,需要到模板页对computed进行配置。在vue 的构造器里边只能有一个computed属性,如果你写多个,只有最后一个computed属性可用,所以要对computed属性进行一个改造,改造时我们使用ES6中的展开运算符”…”。
computed:{
...mapState(["count"]),
count(){
return this.$store.getters.count;
}
},
这样的话,在每次count 的值发生变化的时候,都会进行加100的操作。
另外getters还有一种简化写法:用mapGetters简化
用mapGetters简化模板写法
(1)首先用import引入我们的mapGetters
import { mapState,mapMutations,mapGetters } from 'vuex';
(2)在computed属性中加入mapGetters
...mapGetters(["count"])
完整代码:
Count.vue
<template>
<div>
<h2>{{msg}}</h2>
<hr/>
<h3>{{$store.state.a.count}} = {{count}}</h3>
<div>
<button @click="$store.commit('add',10)">+</button>
<button @click="$store.commit('reduce')">-</button>
</div>
<div>
<p>
<button @click="add(10)">add</button>
<button @click="reduce">reduce</button>
</p>
</div>
</div>
</template>
<script>
import store from '../store'
import {
mapMutations,
mapGetters,
mapActions
} from 'vuex'
export default{
data () {
return {
msg: 'Hello Vuex'
}
},
computed: {
// ...mapState(["count"]),
count () {
return this.$store.state.a.count
},
...mapGetters(['count'])
},
store
}
</script>
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// state访问状态对象
const state = {
count: 1
}
// mutations修改状态
const mutations = {
add (state, n) {
state.count += n
},
reduce (state) {
state.count--
}
}
// getters计算过滤操作
const getters = {
// count: (state) => {
// state.count += 100
// }
count (state) {
state.count += 100
}
}
// module模块组
const moduleA = {
state,
mutations,
getters,
actions
}
export default new Vuex.Store({
// state,
// mutations,
// getters
module: { a: moduleA }
})
在每次count 的值发生变化的时候,都会进行加100的操作