新聞中心
本篇文章為大家展示了如何在Vuex中使用getters屬性,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
wrapGetters初始化getters,接受3個參數(shù),store表示當(dāng)前的Store實例,moduleGetters當(dāng)前模塊下所有的getters,modulePath對應(yīng)模塊的路徑
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不允許重復(fù),否則會報錯 return } store._wrappedGetters[getterKey] = function `wrappedGetter` (store{ // 將每一個getter包裝成一個方法,并且添加到store._wrappedGetters對象中, return rawGetter( //執(zhí)行g(shù)etter的回調(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}
1 應(yīng)用場景
假設(shè)我們在 Vuex 中定義了一個數(shù)組:
const store = new Vuex.Store({ state: { list:[1,3,5,7,9,20,30] } ... })
業(yè)務(wù)場景希望過濾出大于 5 的數(shù)。馬上想到的方法可能的是:在組件的計算屬性中進行過濾:
{{list}}
效果:
功能雖然實現(xiàn)了,但如果其它組件也需要過濾后的數(shù)據(jù),那么就得把 index.vue 中的計算過濾代碼復(fù)制出來。如果過濾規(guī)則發(fā)生變化,還得一一修改這些組件中的計算屬性,很難維護。這種場景下,我們就可以使用 getters 屬性啦O(∩_∩)O~
2 基礎(chǔ)用法
main.js:
const store = new Vuex.Store({ state: { list: [1, 3, 5, 7, 9, 20, 30] }, getters: { filteredList: state => { return state.list.filter(item => item > 5) } } })
index.vue:
效果達(dá)到了,而且只需要在一處維護過濾規(guī)則即可。
3 內(nèi)部依賴
getter 可以依賴其它已經(jīng)定義好的 getter。比如我們需要統(tǒng)計過濾后的列表數(shù)量,就可以依賴之前定義好的過濾函數(shù)。
main.js:
const store = new Vuex.Store({ state: { list: [1, 3, 5, 7, 9, 20, 30] }, getters: { filteredList: state => { return state.list.filter(item => item > 5) }, listCount: (state, getters) => { return getters.filteredList.length; } } })
index.vue:
過濾后的列表:{{list}}
列表長度:{{listCount}}
效果:
上述內(nèi)容就是如何在Vuex中使用getters屬性,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計公司行業(yè)資訊頻道。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
文章題目:如何在Vuex中使用getters屬性-創(chuàng)新互聯(lián)
當(dāng)前網(wǎng)址:http://fisionsoft.com.cn/article/ghooi.html