我正在使用 pinia 和 vue3,但这个问题适用于所有状态管理结构。
在操作中,我应该返回结果然后覆盖(或改变)状态还是直接修改状态作为副作用?
示例1:返回结果然后在组件处重新分配
const exampleStore = createStore({
state: { someState: 1 },
actions: {
async getNewState() {
const newState = await get();
return newState;
}
}
});
//...then in some component in different file...
exampleStore.someState = await exampleStore.getNewState();
示例2:直接修改状态作为副作用
const exampleStore = createStore({
state: { someState: 1 },
actions: {
async getNewState() {
const newState = await get();
this.someState = newState; // assign directly as a side-effect
}
}
});
虽然两种方法都很好,但我想知道哪种方法更值得推荐。
如果使用example1,则在组件中填写状态值。我通常使用example2,不需要在组件中填充状态值。但我添加了一个函数来重置状态值以返回初始值。