在Vuex中,mapActions
辅助函数用于将组件的方法映射到Vuex store中的action,简化组件与store的交互。以下是使用mapActions
的详细步骤:
假设我们有一个store,其中包含一些actions:
// store/index.js
import { createStore } from 'vuex'
const store = createStore({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
},
actions: {
incrementAsync(context) {
setTimeout(() => {
context.commit('increment')
}, 1000)
},
decrementAsync(context) {
setTimeout(() => {
context.commit('decrement')
}, 1000)
},
// 带参数的action
incrementBy(context, payload) {
context.commit('increment', payload)
}
}
})
export default store
mapActions
通常有两种使用方式:
当组件方法名与action名相同时,可以使用数组形式:
import { mapActions } from 'vuex'
export default {
methods: {
// 将this.incrementAsync()映射为this.$store.dispatch('incrementAsync')
...mapActions([
'incrementAsync',
'decrementAsync'
])
}
}
当需要重命名组件方法时,可以使用对象形式:
import { mapActions } from 'vuex'
export default {
methods: {
// 将this.add()映射为this.$store.dispatch('incrementAsync')
...mapActions({
add: 'incrementAsync',
subtract: 'decrementAsync'
})
}
}
映射完成后,可以直接在模板中调用这些方法:
<template>
<div>
<button @click="incrementAsync">异步增加</button>
<button @click="subtract">异步减少</button>
<button @click="incrementBy(5)">增加5(带参数)</button>
</div>
</template>
如果action需要参数,调用时直接传递即可:
// 在组件中
methods: {
...mapActions(['incrementBy']),
handleClick() {
// 传递参数
this.incrementBy(5)
}
}
mapActions
映射的方法本质上是调用this.$store.dispatch()
的语法糖...
合并useStore
钩子替代mapActions
通过mapActions
,可以使组件代码更简洁,减少直接使用this.$store.dispatch
的重复代码。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。