1.什麼是
getters
vue
在介紹state中咱們瞭解到,在Store
倉庫裏,state
就是用來存放數據,如果對數據進行處理輸出,好比數據要過濾,通常咱們能夠寫到computed
中。可是若是不少組件都使用這個過濾後的數據,好比餅狀圖組件和曲線圖組件,咱們是否能夠把這個數據抽提出來共享?這就是getters
存在的意義。咱們能夠認爲,【getters】是store的計算屬性。vuex
2.如何使用segmentfault
定義:咱們能夠在store
中定義getters
,第一個參數是stateapp
const getters = {style:state => state.style}
傳參:定義的Getters
會暴露爲store.getters
對象,也能夠接受其餘的getters
做爲第二個參數;函數
使用:源碼分析
computed: { doneTodosCount () { return this.$store.getters.doneTodosCount}
3.mapGettersthis
mapGetters
輔助函數僅僅是將store
中的getters
映射到局部計算屬性中,用法和mapState
相似code
import { mapGetters } from 'vuex' computed: { // 使用對象展開運算符將 getters 混入 computed 對象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter',])} //給getter屬性換名字 mapGetters({ // 映射 this.doneCount 爲 store.getters.doneTodosCount doneCount: 'doneTodosCount' })
4.源碼分析對象
wrapGetters
初始化getters
,接受3個參數,store
表示當前的Store
實例,moduleGetters
當前模塊下全部的getters
,modulePath
對應模塊的路徑get
function `wrapGetters` (store, moduleGetters, modulePath) { Object.keys(moduleGetters).forEach(getterKey => { // 遍歷先全部的getters const rawGetter = moduleGetters[getterKey] if (store._wrappedGetters[getterKey]) { console.error(`[vuex] duplicate getter key: ${getterKey}`) // getter的key不容許重複,不然會報錯 return } store._wrappedGetters[getterKey] = function `wrappedGetter` (store{ // 將每個getter包裝成一個方法,而且添加到store._wrappedGetters對象中, return rawGetter( //執行getter的回調函數,傳入三個參數,(local state,store getters,rootState) getNestedState(store.state, modulePath), // local state //根據path查找state上嵌套的state store.getters, // store上全部的getters store.state // root state)}}) } //根據path查找state上嵌套的state function `getNestedState` (state, path) { return path.length ? path.reduce((state, key) => state[key], state): state}