You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 14:05:36