You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中遍历Proxy数组遇异常:toRaw后数组无法正常遍历求助

Vue响应式数组遍历问题解决方案

问题原因

  • 控制台console.log的惰性求值特性:打印时仅保存数组引用,展开面板时才读取内存中的最新值,导致“显示为空但展开有内容”的错觉,而length是打印瞬间的真实值。
  • 误用toRaw:Vue3响应式数组本身支持直接遍历,无需转换为原始对象。

正确解决方法

1. 确保遍历时机在元素添加之后

如果元素是异步添加(比如接口请求、定时器),必须等待添加完成再遍历:

<script setup>
import { ref, onMounted } from 'vue'
const exampleArray = ref([])

// 模拟异步数据获取
async function loadData() {
  const data = await new Promise(resolve => setTimeout(() => resolve(['a', 'b', 'c']), 1000))
  exampleArray.value = data
}

onMounted(async () => {
  await loadData()
  // 异步操作完成后遍历
  exampleArray.value.forEach(item => console.log(item))
})

// 其他函数中遍历
function traverseArray() {
  exampleArray.value.forEach(item => console.log(item))
}
</script>

2. Options API直接遍历

Options API中直接操作this.exampleArray即可,不需要toRaw:

<script>
export default {
  data() {
    return {
      exampleArray: []
    }
  },
  mounted() {
    // 同步添加元素
    this.exampleArray.push('x', 'y', 'z')
    // 直接遍历
    this.exampleArray.forEach(item => console.log(item))
  },
  methods: {
    anotherTraverse() {
      this.exampleArray.forEach(item => console.log(item))
    }
  }
}
</script>

3. 必要时正确使用toRaw

如果确实需要原始数组,务必在元素添加完成后调用toRaw:

import { toRaw } from 'vue'

// 元素添加完成后执行
const rawArr = toRaw(this.exampleArray)
console.log(rawArr.length) // 此时长度正确
rawArr.forEach(item => console.log(item))

内容的提问来源于stack exchange,提问作者qsxdrgb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 14:52:43