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 } = store
name // "eduardo"
doubleCount // 2
return {
// will always be "eduardo"
name,
// will always be 2
doubleCount,
// this one will be reactive
doubleValue: 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) property
const { name, doubleCount } = storeToRefs(store)
// the increment action can be just extracted
const { increment } = store
return {
name,
doubleCount
increment,
}
},
})
修改数据状态
通过 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(); } ```