Vue3中如何通过Pinia的Action动态添加Store State新属性
在Pinia中通过Action动态添加State属性的正确方法
你当前的代码无法实现需求,因为Action里返回新对象不会更新Pinia的State——Pinia的State是由Vue的响应式系统管理的,必须直接修改State实例或者使用官方提供的方法。
方案一:直接赋值添加属性
Pinia的State对象是被Vue的reactive包装过的响应式对象,你可以直接通过this访问并添加新属性:
import { defineStore } from "pinia"; export const useAdvanceListingsFilterStore = defineStore( "advance-listing-filters", { state: () => { return { firstName: "john", }; }, actions: { setLastName(payload) { // 直接给当前State添加新属性 this.lastName = payload; }, }, } );
方案二:使用$patch方法(推荐批量修改时用)
如果需要一次性修改多个State属性,Pinia提供了$patch方法,也支持添加新属性:
import { defineStore } from "pinia"; export const useAdvanceListingsFilterStore = defineStore( "advance-listing-filters", { state: () => { return { firstName: "john", }; }, actions: { setLastName(payload) { this.$patch({ lastName: payload }); }, }, } );
验证效果
在组件中使用Store时,调用setLastName后即可访问新增的属性:
import { useAdvanceListingsFilterStore } from "@/stores/your-store-path"; const store = useAdvanceListingsFilterStore(); store.setLastName("Doe"); console.log(store.firstName); // 输出 "john" console.log(store.lastName); // 输出 "Doe"
内容的提问来源于stack exchange,提问作者Ali Raza
相关产品推荐
相关产品推荐

