Vuex之理解Getters

理解Getters

1.什麼是gettersvue

  • 在介紹state中咱們瞭解到,在Store倉庫裏,state就是用來存放數據,如果對數據進行處理輸出,好比數據要過濾,通常咱們能夠寫到computed中。可是若是不少組件都使用這個過濾後的數據,好比餅狀圖組件和曲線圖組件,咱們是否能夠把這個數據抽提出來共享?這就是getters存在的意義。咱們能夠認爲,【getters】是store的計算屬性。vuex


 2.如何使用segmentfault

  • 定義:咱們能夠在store中定義getters,第一個參數是stateapp

    const getters = {style:state => state.style}
  • 傳參:定義的Getters會暴露爲store.getters對象,也能夠接受其餘的getters做爲第二個參數;函數

  • 使用:源碼分析

    computed: {
    doneTodosCount () {
        return this.$store.getters.doneTodosCount}

3.mapGettersthis

  • mapGetters輔助函數僅僅是將store中的getters映射到局部計算屬性中,用法和mapState相似code

    import { mapGetters } from 'vuex'
    computed: {
       // 使用對象展開運算符將 getters 混入 computed 對象中
        ...mapGetters([
        'doneTodosCount',
        'anotherGetter',])}
     //給getter屬性換名字
      mapGetters({
     // 映射 this.doneCount 爲 store.getters.doneTodosCount
      doneCount: 'doneTodosCount'
    })

4.源碼分析對象

  • wrapGetters初始化getters,接受3個參數,store表示當前的Store實例,moduleGetters當前模塊下全部的gettersmodulePath對應模塊的路徑get

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(
              //執行getter的回調函數,傳入三個參數,(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}
相關文章
相關標籤/搜索