简体   繁体   English

在 Vue.js 3 中搜索反应阵列

[英]Searching a reactive array in Vue.js 3

In Vue.js 3 (beta), I have defined an array using reactive , as I want to bind its contents to some UI controls in a loop.在 Vue.js 3 (beta) 中,我使用reactive定义了一个数组,因为我想将其内容绑定到循环中的一些 UI 控件。 So far, this works and everything is fine.到目前为止,这行得通,一切都很好。

Now, I need to update a value within this array, which means I need to run a find or a findIndex on this array.现在,我需要更新这个数组中的一个值,这意味着我需要在这个数组上运行findfindIndex Since the array is being proxied by Vue.js, this doesn't work as expected: The proxy is just not a simple plain old array.由于该阵列由 Vue.js 代理,因此无法按预期工作:代理不是简单的普通旧阵列。

What I did is get a copy using toRaw , run findIndex on that one, and then update the original array using the index.我所做的是使用toRaw获取副本,在该副本上运行findIndex ,然后使用索引更新原始数组。 This works, but of course it doesn't seem to be very elegant.这行得通,但当然它似乎不是很优雅。

Is there a better way to approach this?有没有更好的方法来解决这个问题?

PS: It's fine if it's a solution that only works in Vue 3, I don't care about the 2.x series. PS:如果是仅适用于Vue 3的解决方案就可以,我不在乎2.x系列。

All the array's methods are still accessible through the Proxy , so you can still use find or findIndex on it:仍然可以通过Proxy访问所有数组的方法,因此您仍然可以在其上使用findfindIndex

import { reactive } from 'vue'

const items = reactive([1,2,3])

console.log(items.find(x => x % 2 === 0))
console.log(items.findIndex(x => x % 2 === 0))

 const MyApp = { setup() { const items = Vue.reactive([1,2,3]) return { items, addItem() { items.push(items.length + 1) }, logFirstEvenValue() { console.log(items.find(x => x % 2 === 0)) }, logFirstEvenIndex() { console.log(items.findIndex(x => x % 2 === 0)) }, incrementItems() { for (let i = 0; i < items.length; i++) { items[i]++ } } } } } Vue.createApp(MyApp).mount('#app')
 <script src="https://unpkg.com/vue@3.0.0-rc.5"></script> <div id="app"> <button @click="logFirstEvenValue">Log first even item</button> <button @click="logFirstEvenIndex">Log index of first even item</button> <button @click="incrementItems">Increment items</button> <button @click="addItem">Add item</button> <ul> <li v-for="item in items">{{item}}</li> </ul> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM