问题描述
在Vue.js 3(测试版)中,我已经使用reactive
定义了一个数组,因为我想将其内容绑定到循环中的某些UI控件。到目前为止,一切正常,一切正常。
现在,我需要更新此数组中的值,这意味着我需要在此数组上运行find
或findIndex
。由于该数组由Vue.js代理,因此无法按预期工作:代理不是简单的普通旧数组。
我所做的是使用toRaw
获得一份副本,对该副本运行findIndex
,然后使用索引更新原始数组。这行得通,但是当然看起来并不优雅。
有没有更好的方法来解决这个问题?
PS:如果它是仅适用于Vue 3的解决方案,那我很好,我不在乎2.x系列。
解决方法
仍然可以通过Proxy
访问数组的所有方法,因此您仍然可以在其上使用find
或findIndex
:
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>