vuex中輔助函數的使用方法


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: 'doneTodosCount'
    })
}

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

computed:{
  computed: {
  // 使用對象展開運算符將 getter 混入 computed 對象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
  • 總結:
    • mapState與mapGetters都用computed來進行映射
    • 在組件中映射完成后,通過this.映射屬性名進行使用

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', amount)`
    ]),
}
  • 總結
    • 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'
    ])
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM