0

I have an array in data() { return { exampleArray: [] } }

In mounted(), I call a function that appends to that array.

The result when I console.log(this.exampleArray) is a proxy.

I want to loop through that array in a different function. From looking at other solutions, I should use toRaw to get the array.

So I tried console.log(toRaw(this.examplearray)). What I see in the console is an empty array: [], but if I expand it, I can see the contents inside. Console Picture

However, console.log(toRaw(this.exampleArray).length) is returning length 0. So I can't hit it with a forEach loop.

qsxdrgb
  • 1
  • 1
  • The same way as regular array. That you have this problem suggests that you access data at the wrong moment and use console as debugging tool, which is wrong. The question lacks https://stackoverflow.com/help/mcve . Please, post relevant code instead of describing it – Estus Flask Aug 15 '23 at 00:00
  • Possible duplicate of https://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch – Estus Flask Aug 15 '23 at 00:02

1 Answers1

0

Since Vue 3 there are now two APIs, Options API and Composition API. You're using the older Options API. If you're not familiar with Vue, it's prudent you learn the difference between the APIs so you can identify online resources that are relevant to your chosen API. The Vue docs themselves show Composition API by default but has a toggle in the top-left to change the documentation to Options API.

Regarding your actual question, with Options API you don't have to do anything special. Treat this.exampleArray as a normal JS array. Vue will handle the wrapping/unwrapping of the Proxy for you.

this.exampleArray.forEach(i => console.log(i))

toRaw() is specifically for Composition API. See how the documentation for toRaw is under the "Composition API" section in the sidebar. Because you've chosen to use Options API you wouldn't ever use it.

yoduh
  • 7,074
  • 2
  • 11
  • 21