[英]Searching a reactive array in Vue.js 3
在 Vue.js 3 (beta) 中,我使用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,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.