如何在Pinia Action中获取仅含状态值的完整State对象
在Pinia Action中获取纯State对象的方法
在Pinia的Action里,你可以通过this.$state直接获取仅包含状态值的对象,它不会包含Action、Getter等Store的方法属性。
修改后的示例代码:
export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, name: "apple", color: "green", }), actions: { myaction() { const wholeState = this.$state; // 返回纯状态对象 {count: 0, name: "apple", color: "green"} console.log(wholeState); }, }, })
额外说明:
- 如果需要修改状态对象但不想影响原状态,可以生成副本:
// 复杂嵌套结构用structuredClone深拷贝 const stateCopy = structuredClone(this.$state); // 浅层次结构用扩展运算符 const stateCopy = {...this.$state};
内容的提问来源于stack exchange,提问作者rendom
相关产品推荐
相关产品推荐

