Pinia 数组更改时如何更新多个 Vue 3 组件

Scu*_*ket 4 vue.js vuejs3 pinia

我无法让访问同一商店的多个组件响应更新,直到我弄乱 dom 元素来触发新的渲染。

在我的 Pinia 商店中,我有一个数组和一个更新方法:

    let MyArray: IMyItem[] = [
    { id: 1,
      name: "First Item",
    }, ....
    let SelectedItem = MyArray[0]
    const AddItem = ( n: string, ) => {       
        MyArray.push({ id: createId(), name: n, });
        };

    return { MyArray, SelectedItem, AddItem  }
Run Code Online (Sandbox Code Playgroud)

在一个 Vue 组件中,我有文本输入和一个用于调用商店方法的按钮:

    function handle() {store.AddItem(name.value));
Run Code Online (Sandbox Code Playgroud)

在另一个 Vue 组件中,在同一个父组件上,我使用 for 循环来显示允许选择项目:

    <div v-for="item in store.MyArray">
          <input type="radio"...
Run Code Online (Sandbox Code Playgroud)

这些努力没有改变:

    const { MyArray } = storeToRefs(store);
    const myArray = reactive(store.MyArray);
    // also watching from both components...
    watch(store.MyArray, (n, o) => console.dir(n));
    // also... lots of other stuff.
    const myArray = reactive(store.MyArray);
    watch(myArray, (n, o) => console.dir(n));
Run Code Online (Sandbox Code Playgroud)

我还通过向商店的方法添加字符串返回来尝试<form @submit.prevent="handle">触发。nextTick

我认为点击周围使其起作用的原因是因为我正在更改商店的SelectedItem,并且其反应性要求重新渲染,就像对于v-model标签一样。

文档说 Array.push 应该完成它的工作...它只是在v-for.

触发dom更新需要什么?谢谢!

ton*_*y19 7

正如评论所指出的,主要问题是您的存储状态没有使用 Reactivity API 声明,因此状态更改不会触发观察者,也不会导致重新渲染。

解决方案是将其声明MyArray为 areactiveSelectedItema ref

// store.js
import { defineStore } from 'pinia'
import type { IMyItem } from './types'
import { createId } from './utils'
               
import { ref, reactive } from 'vue'

export const useItemStore = defineStore('item', () => {
                   
  let MyArray = reactive([{ id: createId(), name: 'First Item' }] as IMyItem[])
                     
  let SelectedItem = ref(MyArray[0])
  const AddItem = (n: string) => {
    MyArray.push({ id: createId(), name: n })
  }

  return { MyArray, SelectedItem, AddItem }
})
Run Code Online (Sandbox Code Playgroud)

如果使用storeToRefs(),请确保在更新时设置ref的属性:.valueSelectedItem

// MyComponent.vue
const store = useItemStore()
const { SelectedItem, MyArray } = storeToRefs(store)
const selectItem = (id) => {
                 
  SelectedItem.value = MyArray.value.find((item) => item.id === id)
}
Run Code Online (Sandbox Code Playgroud)

但在这种情况下,直接使用 props 会更简单store

// MyComponent.vue
const store = useItemStore()
const selectItem = (id) => {
  store.SelectedItem = store.MyArray.find((item) => item.id === id)
}
Run Code Online (Sandbox Code Playgroud)

演示