vuex 调用actions
时间: 2023-10-17 22:22:04 浏览: 41
在 Vue.js 应用程序中,我们可以使用 Vuex 来管理应用程序的状态。Vuex 中的 actions 用于处理异步操作并提交 mutations 来更新状态。下面是调用 actions 的步骤:
1. 在 Vue 组件中引入 Vuex 的辅助函数 `mapActions`:
```javascript
import { mapActions } from 'vuex'
```
2. 在组件的 `methods` 中使用 `mapActions` 辅助函数来将 actions 映射为组件的方法:
```javascript
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
])
}
```
3. 调用映射后的方法来触发 actions:
```javascript
this.increment()
this.incrementBy(10)
```
注意:上述示例中的 `increment` 和 `incrementBy` 是 actions 的名称,需要在 Vuex store 中定义。示例中使用的是 `mapActions` 辅助函数的简化写法,也可以使用完整写法来进行调用:
```javascript
methods: {
...mapActions({
add: 'increment', // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
addBy: 'incrementBy' // 将 `this.addBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
})
}
```