1. 程式人生 > 程式設計 >vuex的輔助函式該如何使用

vuex的輔助函式該如何使用

目錄
  • mapState
  • mapGetters
  • mapMutations
  • mapActios
  • 多個modules

mapState

import { mapState } from 'vuex'

export default {
  // ...
  computed:{
     ...mapState({
         // 箭頭函式可使程式碼更簡練
         count: state => state.count,// 傳字串引數 'count' 等同於 `state => state.count`
         countAlias: 'count',// 為了能夠使用 `this` 獲取區域性狀態,必須使用常規函式
         countPlusLocalState (state) {
             return state.count + this.localCount
         }
  	})
  }
}

定義的屬性名與state中的名稱相同時,可以傳入一個數組

//定義state
const state={
    count:1,}

//在元件中使用輔助函式
computed:{
    ...mapState(['count'])
}

mapGetters

computed:{
    ...mapGetters({
      // 把 `this.doneCount` 對映為 `this.$store.getters.doneTodosCount`
      doneCount: 'doneTodosCounwww.cppcns.comt'
    })
}

當屬性名與getters中定義的相同時,可以傳入一個數組

computed:{
  computed: {
  // 使用物件展開運算子將 getter 混入 computed 物件中
    ...mapGetters([
      'doneTodosCount','anotherGetter',// ...
    ])
  }
}

總結:

  • mapState與mapGetters都用computed來進行對映
  • 在元件中對映完成後,通過this.對映屬性http://www.cppcns.com名進行使用

mapMutations

methods:{
    ...mapMutations({
        add: 'increment' // 將 `this.add()` 對映為 `this.$store.commit('increment')`
    })
}

當屬性名與mapMutatios中定義的相同時,可以傳入一個數組

methods:{
    ...mapMutations([
        'increment',// 將 `this.increment()` 對映為 `this.$store.commit('increment')`

        // `mapMutations` 也支援載荷:
        'incrementBy' // 將 `this.incrementBy(amount)` 對映為 `this.$store.commit('incrementBy',amount)`
    ]),}
程式設計客棧

mapActios

mathods:{
    ...mapActions({
        add: 'increment' // 將 `this.add()` 對映為 `this.$store.dispatch('increment')`
    })
}

當屬性名與mapActios中定義的相同時,可以傳入一個數組

methods:{
    ...mapActions([
        'increment',// 將 `this.increment()` 對映為 `this.$store.dispatch('increment')`	
    程式設計客棧    // `mapActions` 也支援載荷:
        'incrementBy' // 將 `this.incrementBy(amount)` 對映為 `this.$store.dispatch('incrementBy',}

總結

  • mapMutations與mapActios都在methods中進行對映
  • 對映之後變成一個方法

多個modules

在不使用輔助函式的時候,

this.$store.commit('app程式設計客棧/addCount')

使用輔助函式,輔助函式的第一個引數給定名稱空間的路徑

computed: {
  ...mapState('some/nested/module',{
    a: state => state.a,b: state => state.b
  })
},methods: {
  ...mapActions('some/nested/module',[
    'foo',// -> this.foo()
    'bar' // -> this.bar()
  ])
}

或者使用 createNamespacedHelpers函式來建立一個基於名稱空間的輔助函式

import { createNamespacedHelpers } from 'vuex'

const { mapState,mapActions } = createNamespacedHelpers('some/nested/module') //給定路徑
//使用方法與之前相同
export default {
  computed: {
    // 在 `some/nested/module` 中查詢
    ...mapState({
      a: state => state.a,b: state => state.b
    })
  },methods: {
    // 在 `some/nested/module` 中查詢
    ...mapActions([
      'foo','bar'
    ])
  }
}

以上就是vuex的輔助函式該如何使用的詳細內容,更多關於vuex的輔助函式的資料請關注我們其它相關文章!