Vuex中的Getters

在Store倉庫中,state是用來存放數據的,若是要對數據進行處理輸出,好比數據要過濾,通常咱們能夠寫到computed中。可是若是不少組件都使用這個過濾後的數據,咱們能夠考慮把這個數據提出來共享。這就是getters存在的意義,咱們能夠將getters認爲是 store 的計算屬性(computed)。vue

就像計算屬性同樣,getters 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變纔會被從新計算。vuex

示例:

假設有一個關於考試分數的數組,咱們須要在不少頁面中使用,可是隻須要顯示不及格的成績,此時咱們就要過濾掉不符合要求的數據。數組

以下所示:緩存

computed: { 
    scoreArr(){ 
        return this.$store.state.score.filter(item => item < 60) 
    }
}

若是不少地方要用到此屬性,咱們要麼複製這個函數,或者抽取到一個共享函數而後在多處導入它,可是無論哪一種方式都不是很理想。函數

Getters的使用

Vuex 容許咱們在 store 中定義getters,第一個參數爲state:this

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

Getters還會將store.getters對象暴露出去,咱們能夠以屬性的形式訪問這些值:code

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

Getters 也能夠接受其餘的 getters 做爲第二個參數:對象

getters: {
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

mapGetters 輔助函數

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

首先也是須要引入 mapGetters 函數:it

import { mapGetters } from 'vuex'

引入後就能夠開始使用了:

import { mapGetters } from 'vuex'

export default {
  computed: {
      // 使用對象展開運算符將getters混入computed對象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
    ])}
}

若是想給一個 getters 屬性另取一個名字,可使用對象形式,例如:

// 給getter屬性換名字
mapGetters({
    // 映射this.doneCount爲store.getters.doneTodosCount
     doneCount: 'doneTodosCount'
})
相關文章
相關標籤/搜索