action 方法
约 259 字小于 1 分钟
2025-08-10
简介
Action 相当于组件中的 method。它们可以通过 defineStore() 中的 actions 属性来定义,并且它们也是定义业务逻辑的完美选择。
- 封装业务逻辑
- 处理异步操作
- 修改 store 状态
- 调用其他 actions 或 getters
定义方式
选项式 API
export const useCounterStore = defineStore("main", {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
randomizeCounter() {
this.count = Math.round(100 * Math.random());
},
add() {
this.increment();
},
},
});
组合式 API
defineStore("store", () => {
const count = ref(1);
const double = () => count.value * 2;
const add = (val) => (count.value += val);
return { count, double };
});
使用
访问 store 实例内的其他方法属性
action 内部可以使用 this 来访问挂载到 store 上的 state、getter、action
export const useCounterStore = defineStore("main", {
state: () => ({
count: 0,
name: "",
}),
actions: {
increment() {
this.count++;
},
changeName(name) {
this.name = "";
}
reset() {
this.increment();
this.changeName("");
},
},
});
支持异步操作
export const useCounterStore = defineStore("main", {
actions: {
async fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`)
const data = await response.json()
this.user = data
return data // 可选择返回结果
} catch (error) {
throw new Error('Failed to fetch user data')
}
}
}
}
访问其他 store
import { useOtherStore } from "./other-store";
const otherStore = useOtherStore();
export const useCounterStore = defineStore("main", {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
otherStore.count++;
},
add() {
this.increment();
},
},
});
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于