store 解构得变量修改后没有更新
当我们解构出 store 的变量后,再修改 store 上该变量的值,视图没有更新:
export default defineComponent({setup() {const store = useStore()// ❌ This won't work because it breaks reactivity// it's the same as destructuring from `props`const { name, doubleCount } = storename // "eduardo"doubleCount // 2return {// will always be "eduardo"name,// will always be 2doubleCount,// this one will be reactivedoubleValue: computed(() => store.doubleCount),}},})
这是因为 store 是个 reactive 对象,当进行解构后,会破坏它的响应性。
使用 Pinia 提供 storeToRefs工具方法:
import { storeToRefs } from 'pinia'export default defineComponent({setup() {const store = useStore()// `name` and `doubleCount` are reactive refs// This will also create refs for properties added by plugins// but skip any action or non reactive (non ref/reactive) propertyconst { name, doubleCount } = storeToRefs(store)// the increment action can be just extractedconst { increment } = storereturn {name,doubleCountincrement,}},})
修改数据状态
通过 store.属性名修改单条数据的状态
const changeName = () => {componentStoreObj.name = 'hello pingan8787';}
通过 $patch修改多条数据状态
const changeName = () => {// 参数类型1:对象componentStoreObj.$patch({name: 'hello pingan8787',age: '18',addr: 'xiamen',})// 参数类型2:方法,该方法接收 store 中的 state 作为参数componentStoreObj.$patch(state => {state.name = 'hello pingan8787';state.age = '18';state.addr = 'xiamen';})}
通过 action 方法修改多条数据状态 ```typescript // store.ts import { defineStore } from ‘pinia’;
export default defineStore({ id: ‘testStore’, state: () => { return { name: ‘pingan8787’, age: ‘10’, addr: ‘fujian’ } }, actions: { updateState(){ this.name = ‘hello pingan8787’; this.age = ‘18’; this.addr = ‘xiamen’; } } })
// 使用 const changeName = () => { componentStoreObj.updateState(); } ```
