store 解构得变量修改后没有更新

文档地址:https://pinia.vuejs.org/core-concepts/#using-the-store

当我们解构出 store 的变量后,再修改 store 上该变量的值,视图没有更新:

  1. export default defineComponent({
  2. setup() {
  3. const store = useStore()
  4. // ❌ This won't work because it breaks reactivity
  5. // it's the same as destructuring from `props`
  6. const { name, doubleCount } = store
  7. name // "eduardo"
  8. doubleCount // 2
  9. return {
  10. // will always be "eduardo"
  11. name,
  12. // will always be 2
  13. doubleCount,
  14. // this one will be reactive
  15. doubleValue: computed(() => store.doubleCount),
  16. }
  17. },
  18. })

这是因为 store 是个 reactive 对象,当进行解构后,会破坏它的响应性。
使用 Pinia 提供 storeToRefs工具方法:

  1. import { storeToRefs } from 'pinia'
  2. export default defineComponent({
  3. setup() {
  4. const store = useStore()
  5. // `name` and `doubleCount` are reactive refs
  6. // This will also create refs for properties added by plugins
  7. // but skip any action or non reactive (non ref/reactive) property
  8. const { name, doubleCount } = storeToRefs(store)
  9. // the increment action can be just extracted
  10. const { increment } = store
  11. return {
  12. name,
  13. doubleCount
  14. increment,
  15. }
  16. },
  17. })

修改数据状态

  1. 通过 store.属性名修改单条数据的状态

    1. const changeName = () => {
    2. componentStoreObj.name = 'hello pingan8787';
    3. }
  2. 通过 $patch修改多条数据状态

    1. const changeName = () => {
    2. // 参数类型1:对象
    3. componentStoreObj.$patch({
    4. name: 'hello pingan8787',
    5. age: '18',
    6. addr: 'xiamen',
    7. })
    8. // 参数类型2:方法,该方法接收 store 中的 state 作为参数
    9. componentStoreObj.$patch(state => {
    10. state.name = 'hello pingan8787';
    11. state.age = '18';
    12. state.addr = 'xiamen';
    13. })
    14. }
  3. 通过 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(); } ```