vuex的輔助函數(shù)該如何使用
mapState
import { mapState } from 'vuex'
export default {
// ...
computed:{
...mapState({
// 箭頭函數(shù)可使代碼更簡練
count: state => state.count,
// 傳字符串參數(shù) 'count' 等同于 `state => state.count`
countAlias: 'count',
// 為了能夠使用 `this` 獲取局部狀態(tài),必須使用常規(guī)函數(shù)
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
}
定義的屬性名與state中的名稱相同時,可以傳入一個數(shù)組
//定義state
const state={
count:1,
}
//在組件中使用輔助函數(shù)
computed:{
...mapState(['count'])
}
mapGetters
computed:{
...mapGetters({
// 把 `this.doneCount` 映射為 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
}
當屬性名與getters中定義的相同時,可以傳入一個數(shù)組
computed:{
computed: {
// 使用對象展開運算符將 getter 混入 computed 對象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
總結(jié):
- mapState與mapGetters都用computed來進行映射
- 在組件中映射完成后,通過this.映射屬性名進行使用
mapMutations
methods:{
...mapMutations({
add: 'increment' // 將 `this.add()` 映射為 `this.$store.commit('increment')`
})
}
當屬性名與mapMutatios中定義的相同時,可以傳入一個數(shù)組
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中定義的相同時,可以傳入一個數(shù)組
methods:{
...mapActions([
'increment', // 將 `this.increment()` 映射為 `this.$store.dispatch('increment')`
// `mapActions` 也支持載荷:
'incrementBy' // 將 `this.incrementBy(amount)` 映射為 `this.$store.dispatch('incrementBy', amount)`
]),
}
總結(jié)
- mapMutations與mapActios都在methods中進行映射
- 映射之后變成一個方法
多個modules
在不使用輔助函數(shù)的時候,
this.$store.commit('app/addCount')
使用輔助函數(shù),輔助函數(shù)的第一個參數(shù)給定命名空間的路徑
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函數(shù)來創(chuàng)建一個基于命名空間的輔助函數(shù)
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的輔助函數(shù)該如何使用的詳細內(nèi)容,更多關(guān)于vuex的輔助函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Element-ui之ElScrollBar組件滾動條的使用方法
這篇文章主要介紹了Element-ui之ElScrollBar組件滾動條的使用方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09
Vue項目使用Websocket大文件FileReader()切片上傳實例
這篇文章主要介紹了Vue項目使用Websocket大文件FileReader()切片上傳實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
vue項目中的數(shù)據(jù)變化被watch監(jiān)聽并處理
這篇文章主要介紹了vue項目中的數(shù)據(jù)變化被watch監(jiān)聽并處理,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04

