vue2vuex使用方法action
时间: 2025-07-06 12:46:40 浏览: 8
### Vue 2 中 Vuex Action 的使用
在 Vue 2 应用中,Vuex 提供了一种集中式的状态管理模式。通过 `actions` 可以处理异步操作并提交 mutation 来变更状态[^2]。
#### 创建 Store 实例
定义一个包含初始状态 (`state`) 和修改该状态的方法 (`mutations`) 的 store 对象:
```javascript
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
}
},
})
```
#### 定义 Actions
为了执行一些逻辑后再调用 mutation 或者进行异步任务,在 actions 中实现这些功能更为合适。下面是一个简单的例子展示如何创建和触发 action:
```javascript
// 添加到之前的 store 配置里
actions: {
increment(context) {
context.commit('increment');
},
// 假设有一个延迟增加的操作
asyncIncrement({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000);
}
}
```
这里展示了两种类型的 actions:同步的 `increment` 和模拟网络请求或其他耗时过程后的 `asyncIncrement`.
#### 调用 Actions
可以在组件内部通过 `$store.dispatch()` 方法来分发 (dispatch) 这些 actions :
```html
<template>
<div class="example">
Count is {{ count }}
<button @click="handleClick">Increment</button>
<button @click="handleAsyncClick">Async Increment</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
handleClick() {
this.$store.dispatch('increment'); // 同步动作
},
handleAsyncClick(){
this.$store.dispatch('asyncIncrement'); // 异步动作
}
},
computed:{
count(){
return this.$store.state.count;
}
}
};
</script>
```
此模板提供了一个按钮用于触发不同类型的 increments 操作,并显示当前计数值。
阅读全文
相关推荐



















