Vuex之理解Getters的用法執行個體,vuexgetters執行個體

來源:互聯網
上載者:User

Vuex之理解Getters的用法執行個體,vuexgetters執行個體

1.什麼是getters

在介紹state中我們瞭解到,在Store倉庫裡,state就是用來存放資料,若是對資料進行處理輸出,比如資料要過濾,一般我們可以寫到computed中。但是如果很多組件都使用這個過濾後的資料,比如餅狀圖組件和曲線圖組件,我們是否可以把這個資料抽提出來共用?這就是getters存在的意義。我們可以認為,【getters】是store的計算屬性。

2.如何使用

定義:我們可以在store中定義getters,第一個參數是state

const getters = {style:state => state.style}

傳參:定義的Getters會暴露為store.getters對象,也可以接受其他的getters作為第二個參數;

使用:

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

3.mapGetters

mapGetters輔助函數僅僅是將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個參數,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(       //執行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}  

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.