官網文檔:html
https://vuex.vuejs.org/zh-cn/api.html 最底部vue
mapStatevuex
此函數返回一個對象,生成計算屬性 - 當一個組件須要獲取多個狀態時候,將這些狀態都聲明爲計算屬性會有些重複和冗餘。mapState能夠聲明多個api
須要在組件中引入:數組
import { mapState } from 'vuex'
...mapState({ // ... }) 對象展開運算符函數
mapGettersthis
將store中的多個getter映射到局部組件的計算屬性中spa
組件中引入code
import { mapGetters } from 'vuex'
組件的computed計算屬性中使用htm
1 computed: { 2 3 // 使用對象展開運算符將 getter 混入 computed 對象中 4 ...mapGetters([ 5 6 'doneTodosCount', 7 8 'anotherGetter', 9 10 // ... 11 ]) 12 13 }
或者給getter屬性另起個名字:
mapGetters({ doneCount: 'doneTodosCount' })
mapMutations
將組件中的 methods 映射爲 store.commit 調用(須要在根節點注入store)。
組件中引入:
import { mapMutations } from 'vuex'
組件的methods中使用:兩種方式,傳參字符串數組或者對象,
1 methods: { 2 3 ...mapMutations([ 4 5 'increment', // 將 `this.increment()` 映射爲 `this.$store.commit('increment')` 6 // `mapMutations` 也支持載荷: 7 'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.commit('incrementBy', amount)` 8 ]), 9 10 ...mapMutations({ 11 12 add: 'increment' // 將 `this.add()` 映射爲 `this.$store.commit('increment')` 13 }) 14 15 }
mapActions
將組件的 methods 映射爲 store.dispatch 調用(須要先在根節點注入 store):
組件中引入:
import { mapActions } from 'vuex'
組件的methods中使用:兩種方式,傳參字符串數組或者對象,
1 methods: { 2 3 ...mapActions([ 4 5 'increment', // 將 `this.increment()` 映射爲 `this.$store.dispatch('increment')` 6 // `mapActions` 也支持載荷: 7 'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.dispatch('incrementBy', amount)` 8 ]), 9 10 ...mapActions({ 11 12 add: 'increment' // 將 `this.add()` 映射爲 `this.$store.dispatch('increment')` 13 }) 14 15 }
2018-04-07 17:57:31