Gol*_*den 1 javascript arrays vue.js vuejs3
在 Vue.js 3(测试版)中,我使用 定义了一个数组reactive,因为我想将其内容绑定到循环中的某些 UI 控件。到目前为止,这行得通,一切都很好。
现在,我需要更新这个数组中的一个值,这意味着我需要在这个数组上运行 afind或 a 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))
Run Code Online (Sandbox Code Playgroud)
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')Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1016 次 |
| 最近记录: |