国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 福鼎市| 清原| 若羌县| 三穗县| 金寨县| 福安市| 萨嘎县| 临洮县| 宁蒗| 阿克苏市| 敦煌市| 石城县| 会理县| 抚顺县| 尉氏县| 洪湖市| 青神县| 扎鲁特旗| 托里县| 当阳市| 循化| 嫩江县| 嵊泗县| 金山区| 乐山市| 丰台区| 洛浦县| 漳州市| 驻马店市| 定兴县| 长葛市| 枣庄市| 米泉市| 中江县| 萨嘎县| 宁阳县| 渭源县| 苏尼特左旗| 承德市| 彭泽县| 青岛市|