1.什么是getters
在介紹state中我們了解到,在Store
倉庫里,state
就是用來存放數(shù)據(jù),若是對數(shù)據(jù)進行處理輸出,比如數(shù)據(jù)要過濾,一般我們可以寫到computed
中。但是如果很多組件都使用這個過濾后的數(shù)據(jù),比如餅狀圖組件和曲線圖組件,我們是否可以把這個數(shù)據(jù)抽提出來共享?這就是getters
存在的意義。我們可以認為,【getters】是store的計算屬性。
2.如何使用
定義:我們可以在store
中定義getters
,第一個參數(shù)是state
const getters = {style:state => state.style}
傳參:定義的Getters
會暴露為store.getters
對象,也可以接受其他的getters
作為第二個參數(shù);
使用:
computed: {doneTodosCount () { return this.$store.getters.doneTodosCount}
3.mapGetters
mapGetters
輔助函數(shù)僅僅是將store
中的getters
映射到局部計算屬性中,用法和mapState
類似
import { mapGetters } from 'vuex'computed: { // 使用對象展開運算符將 getters 混入 computed 對象中 ...mapGetters([ 'doneTodosCount', 'anotherGetter',])} //給getter屬性換名字 mapGetters({ // 映射 this.doneCount 為 store.getters.doneTodosCount doneCount: 'doneTodosCount'})
4.源碼分析
wrapGetters
初始化getters
,接受3個參數(shù),store
表示當前的Store
實例,moduleGetters
當前模塊下所有的getters
,modulePath
對應模塊的路徑
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( //執(zhí)行getter的回調(diào)函數(shù),傳入三個參數(shù),(local state,store getters,rootState) getNestedState(store.state, modulePath), // local state //根據(jù)path查找state上嵌套的state store.getters, // store上所有的getters store.state // root state)}}) } //根據(jù)path查找state上嵌套的state function `getNestedState` (state, path) { return path.length ? path.reduce((state, key) => state[key], state): state}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答