gpt4 book ai didi

vue.js - Pinia 数组更改时如何更新多个 Vue 3 组件

转载 作者:行者123 更新时间:2023-12-03 08:06:50 30 4
gpt4 key购买 nike

我无法让访问同一商店的多个组件响应更新,直到我弄乱 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 }

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

    function handle() {store.AddItem(name.value));

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

    <div v-for="item in store.MyArray">
<input type="radio"...

这些努力没有改变:

    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));

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

我认为点击周围使其起作用的原因是因为我正在更改商店的 SelectedItem ,其 react 性要求重新渲染,因为它是 v-model用于标签。

文档说 Array.push 应该完成它的工作...它只是在 v-for 中使用时没有以相同的方式绑定(bind)。 .

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

最佳答案

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

解决方案是声明 MyArray作为 reactive SelectedItem作为 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 }
})

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

// MyComponent.vue
const store = useItemStore()
const { SelectedItem, MyArray } = storeToRefs(store)
const selectItem = (id) => {
👇
SelectedItem.value = MyArray.value.find((item) => item.id === id)
}

但在这种情况下,使用store中的 Prop 会更简单。直接:

// MyComponent.vue
const store = useItemStore()
const selectItem = (id) => {
store.SelectedItem = store.MyArray.find((item) => item.id === id)
}

demo

关于vue.js - Pinia 数组更改时如何更新多个 Vue 3 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72061029/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com