阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里。
该节教程代码可通过npm start运行devServer,在http://localhost:8080/#/index查看效果
Getter的基本使用
代码示例:/lesson21/src/index.js
Vuex中的Getter的作用类似于Vue中的Computed,可以实现在state变化时自动计算出一个新的结果。
在store中配置一个Getter:
getters: {
count (state) {
return state.a + state.b
}
}
代码示例:/lesson21/src/components/Index.vue
在组件Index中,可以通过$store.getters.count就可以读取到相应的值。
<div>count from getters: {{$store.getters.count}}</div>
为了方便使用,通常可以把Getter配置到Computed中:
computed: {
countFromComputed() {
return this.$store.getters.count
}
}
在Template中引用:
<div>count from computed: {{countFromComputed}}</div>
利用Computed更新State
因为Computed属性支持get和set方法,所以能够使用set方法更新State。
首先在Store中设置actions和Mutations。
代码示例:/lesson21/src/store/index.js
mutations: {
addA (state, n) {
state.a += n
},
addB (state, n) {
state.b += n
},
},
actions: {
addA ({commit}, n) {
commit('addA', n)
},
addB ({commit}, n) {
commit('addB', n)
},
},
Index.vue模板中添加<input type=“button” value=“count+5” @click=“addCount(5)” />,调用一个addCount方法,在addCount方法中让countFromComputedSet属性加5。
在computed属性中接收到结果后,将增加的5分配给a属性。
countFromComputedSet: {
get() {
return this.$store.getters.count
},
set(value) {
this.$store.dispatch('addA', 5)
},
},