該節教程代碼可經過npm start運行devServer,在http://localhost:8080/查看效果vue
代碼示例:/lesson21/src/index.jsgit
Vuex中的Getter的做用相似於Vue中的Computed,能夠實如今state變化時自動計算出一個新的結果。 在store中配置一個Getter:github
getters: {
count (state) {
return state.a + state.b
}
}
複製代碼
代碼示例:/lesson21/src/components/Index.vuenpm
在組件Index中,能夠經過$store.getters.count就能夠讀取到相應的值。bash
<div>count from getters: {{$store.getters.count}}</div>
複製代碼
爲了方便使用,一般能夠把Getter配置到Computed中:less
computed: {
countFromComputed() {
return this.$store.getters.count
}
}
複製代碼
在Template中引用:ui
<div>count from computed: {{countFromComputed}}</div>
複製代碼
由於Computed屬性支持get和set方法,因此可以使用set方法更新State。this
首先在Store中設置actions和Mutations。spa
代碼示例:/lesson21/src/store/index.jscode
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)
},
},
複製代碼