国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Vuex之理解Getters的用法實例

2019-11-19 16:47:28
字體:
供稿:網(wǎng)友

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當前模塊下所有的gettersmodulePath對應模塊的路徑

  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)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 太仓市| 陇川县| 专栏| 堆龙德庆县| 龙泉市| 赣州市| 政和县| 桃园市| 南安市| 屯门区| 黑山县| 汝南县| 宜宾县| 屏东市| 望奎县| 化州市| 鹤壁市| 庄浪县| 水富县| 大厂| 苍南县| 原平市| 镇巴县| 金溪县| 南皮县| 乐陵市| 灵丘县| 克山县| 平远县| 富平县| 同德县| 秀山| 体育| 故城县| 岳普湖县| 黄浦区| 南康市| 陆川县| 乐山市| 澄迈县| 孟村|