在Vue.js 3中搜索反应式数组

问题描述

在Vue.js 3(测试版)中,我已经使用reactive定义了一个数组,因为我想将其内容绑定到循环中的某些UI控件。到目前为止,一切正常,一切正常。

现在,我需要更新此数组中的值,这意味着我需要在此数组上运行findfindIndex。由于该数组由Vue.js代理,因此无法按预期工作:代理不是简单的普通旧数组。

我所做的是使用toRaw获得一份副本,对该副本运行findIndex,然后使用索引更新原始数组。这行得通,但是当然看起来并不优雅。

有没有更好的方法来解决这个问题?

PS:如果它是仅适用于Vue 3的解决方案,那我很好,我不在乎2.x系列。

解决方法

仍然可以通过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,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>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...