【问题标题】:Searching a reactive array in Vue.js 3在 Vue.js 3 中搜索反应式数组
【发布时间】:2020-12-06 01:20:49
【问题描述】:

在 Vue.js 3(测试版)中,我使用 reactive 定义了一个数组,因为我想将其内容绑定到循环中的一些 UI 控件。到目前为止,这行得通,一切都很好。

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

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

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

PS:如果是只适用于Vue 3的解决方案就好了,我不关心2.x系列。

【问题讨论】:

    标签: javascript arrays vue.js vuejs3


    【解决方案1】:

    数组的所有方法仍然可以通过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>

    【讨论】:

    • 你说得对——好像我以前做错了什么,但不要问我是什么……我刚刚删除了toRaw 调用,它运行良好?
    猜你喜欢
    • 2020-01-13
    • 2019-04-16
    • 1970-01-01
    • 2022-01-25
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多