Getter是個啥
是個對象,類似于computed裡面的對象
如果我們需要對state對象進行做處理計算,比如說,我們有三家超市,我們想計算三家超市的總營業額。同時還要計算實際的收入,假設成本是200。
同時getter還可以接收其他其他getter
const store = new Vuex.Store({
state: {
shop1: 100,
shop2: 200,
shop3: 300,
},
getters: {
getShopTotal(state) {
return state.shop1 + state.shop2 + state.shop3
},
getShopMoney(state, getters) {
return getters.getShopTotal - 200
}
}
})
computed: {
shopTotal() {
return this.$store.getters.getShopTotal;
},
shopMoney() {
return this.$store.getters.getShopMoney;
}
},
Getter傳參
在上面的例子我們可以返現,getter裡面其實就是一個屬性,我們當然可以讓這些屬性來接收一個函數。
在上面,我們發現,想計算利潤的話需要在裡面減去200,如果不同的超市,都想調用這個getter的話,但是成本不是200的話,就需要寫好多函數,是以我們考慮getter可以接受參數。
getters: {
getShopMoney: function (state, getters) {
return (zhichu) => {
return getters.getShopTotal - 200 - zhichu
}
}
}
computed: {
shopMoney() {
return this.$store.getters.getShopMoney(100);
}
},
mapGetters 輔助函數
mapGetters 輔助函數僅僅是将 store 中的 getter 映射到局部計算屬性,
- 引入mapGetters
import { mapGetters } from 'vuex'
- 使用
computed: {
// 使用對象展開運算符将 getter 混入 computed 對象中
...mapGetters([
'getShopTotal',
'getShopMoney',
]),
或者
mapGetters({
// 把 `this.shopTotal` 映射為 `this.$store.getters.getShopTotal`
shopTotal: 'getShopTotal'
})
}