Vuex 允许我们在store中定义“getter”(可以认为是store的计算属性)。就像计算属性一样,getter的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
getters的作用
对于getters的理解主要作用是对state属性进行计算,可以理解类似于Vue中computed。接下来让我通过一个例子如何使用这两个功能的。
还是以我们上一讲的累加器为例,在getter.js中增加getCount,内容如下:
|
1
2
3
4
5
6
7
8
9
10
|
const getters = { getNum (state) {
return state.num
},
getCount (state) {
return state.count
}
}export default getters
|
在组件中如何使用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<template> <div class="getter">
{{ count }}
<button @click="add">ADD State</button>
</div>
</template><script>export default {
data () {
return {}
},
computed: {
count () {
return this.$store.getters.getCount
}
},
methods: {
add () {
this.$store.commit('add')
}
}
}</script> |
this.$store调用
|
1
|
this.$store.getters.getCount
|
引用store来调用
|
1
2
3
|
import store from '@/store/store.js'
store.getters.getCount |
mapGetters 辅助函数
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<template> <div class="getter">
{{ getCount }}
<button @click="add">ADD State</button>
</div>
</template><script>import { mapGetters } from 'vuex'
export default {
data () {
return {}
},
computed: {
...mapGetters(['getCount'])
},
methods: {
add () {
this.$store.commit('add')
}
}
}</script> |