Vuex之理解Getters的用法實例
1.什么是getters
在介紹state中我們了解到,在Store倉庫里,state就是用來存放數(shù)據,若是對數(shù)據進行處理輸出,比如數(shù)據要過濾,一般我們可以寫到computed中。但是如果很多組件都使用這個過濾后的數(shù)據,比如餅狀圖組件和曲線圖組件,我們是否可以把這個數(shù)據抽提出來共享?這就是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的回調函數(shù),傳入三個參數(shù),(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}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue.js?element-plus使用圖標不顯示問題的解決方式
近期在學習Vue時用elementUI時發(fā)現(xiàn)圖標在頁面上顯示不出來,所以這篇文章主要給大家介紹了關于Vue.js?element-plus使用圖標不顯示問題的解決方式,需要的朋友可以參考下2022-09-09
vue3?+?async-validator實現(xiàn)表單驗證的示例代碼
表單驗證可以有效的過濾不合格的數(shù)據,減少服務器的開銷,并提升用戶的使用體驗,今天我們使用?vue3?來做一個表單驗證的例子,需要的朋友跟隨小編一起學習下吧2022-06-06
vue3+ts+elementPLus實現(xiàn)v-preview指令
本文主要介紹了vue3+ts+elementPLus實現(xiàn)v-preview指令,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05
Vue使用Less與Scss實現(xiàn)主題切換方法詳細講解
目前,在眾多的后臺管理系統(tǒng)中,換膚功能已是一個很常見的功能。用戶可以根據自己的喜好,設置頁面的主題,從而實現(xiàn)個性化定制。目前,我所了解到的換膚方式,也是我目前所掌握的兩種換膚方式,想同大家一起分享2023-02-02
Vue使用 onMounted 確保在組件掛載后執(zhí)行異步操作示例詳解
在 Vue.js 或其他類似框架中,使用 onMounted 是為了確保在組件掛載后執(zhí)行異步操作,這篇文章主要介紹了Vue使用onMounted確保在組件掛載后執(zhí)行異步操作,需要的朋友可以參考下2023-06-06

