getter
getters 可以理解為 vuex 中的 computed,和 vue 中的 computed 類似,都是用來計算 state 然後生成新的資料 ( 狀態 ) 的。
在上面的案例當中,如果想得到的 state 最終為一個帶了幣種的金額,只要給一個統一的出口,返回統一的資料模式。
簡單實現
store.js
import Vue from `vue`
import Vuex from `vuex`
Vue.use(Vuex)
let state = {
count: 0
}
let getters = {
total: state => {
return `$` + state.count;
}
}
let mutations = {
increment(_state, n){
_state.count += n || 1;
},
decrement(){
state.count -= 1;
}
}
const store = new Vuex.Store({
state,
getters,
mutations
})
export default store
getter 通過屬性訪問
<h3>count-{{$store.getters.total}}</h3>
getter 通過方法訪問
如果上面的方法想改變貨幣符號,那就要通過傳參方式來解決
let getters = {
total: (state) => (symbol) => {
return (symbol || `$`) + state.count;
}
}
<h3>count-{{$store.getters.total(`¥`)}}</h3>
mapGetters 輔助函式
<template>
<div>
<h3>count-{{total(`¥`)}}</h3>
</div>
</template>
<script>
import common from `../../common/common.js`
import {mapState, mapMutations, mapGetters} from `vuex`;
export default {
computed: {
...mapGetters([
`total`
])
}
}
</script>
mapGetters 輔助函式之別名
<template>
<div>
<h3>count-{{amount(`¥`)}}</h3>
</div>
</template>
<script>
import common from `../../common/common.js`
import {mapState, mapMutations, mapGetters} from `vuex`;
export default {
computed: {
...mapGetters({
amount: `total`
})
}
}
</script>