在vuex中getter至關於計算屬性
1.在store.js中寫上:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
count:0,
},
mutations:{
changeCount:function (state,count) {
state.count=count
console.log(state.count)
},
getters: {
// 單個參數
countDouble: function(state){
return state.count * 2
},
// 兩個參數
CountDoubleAndDouble: function(state, getters) {
return getters.countDouble * 2
}
}
})
2.在組件的頁面寫:(這裏調用的方式有兩種)
第一種:
<div class="add" @click="changeCount">+</div>
一個參數:{{countDouble}}
兩個參數{{CountDoubleAndDouble}} <br />
</div>
data () {
return {
Acount:0,
}
},
(............重點............)
countDouble: function(){
return this.$store.getters.countDouble
},
countDoubleAndDouble: function(){
return this.$store.getters.countDoubleAndDouble
},
methods:{
changeCount(){
this.Acount++;
this.$store.commit('changeCount',this.Acount);
}
}
第二種:
import { mapGetters } from 'vuex'
...mapGetters([
'countDouble',
'CountDoubleAndDouble',
]),
不管用哪種結果都是同樣的,看我的喜愛...........
我將getters屬性理解爲全部組件的computed屬性, 也就是計算屬性. vuex的官方文檔也是說到能夠將getter理解爲store的計算屬性, getters的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變纔會被從新計算。
我將mutaions理解爲store中的methods, mutations對象中保存着更改數據的回調函數,該函數名官方規定叫type, 第一個參數是state, 第二參數是payload, 也就是自定義的參數.
actions 相似於 mutations,不一樣在於:actions提交的是mutations而不是直接變動狀態actions中能夠包含異步操做, mutations中絕對不容許出現異步actions中的回調函數的第一個參數是context, 是一個與store實例具備相同屬性和方法的對象
複製代碼