Vue directive v-for="thing in collection" vs "thing of collection"

Viewed 2217

In the official Vue.js documentation, all of the examples for the v-for directive have the format:

v-for="thing in collection"

where collection includes arrays and objects. Further, the documentation states:

You can also use of as the delimiter instead of in, so that it is closer to JavaScript’s syntax for iterators.

This answer explains the difference between for..in and for..of loops in vanilla JavaScript. As I understood it, for..in is used to loop over an object's properties and for..of is used to loop over an iterable's elements.

My question is, do of and in carry the same meaning in Vue as they do in vanilla JavaScript?

1 Answers

They do not

In Vue.js, for..of and for..in are equivalent and interchangeable. Iterating in Vue.js is very flexible and can handle a wide variety of objects and types (Even integers! Take note, TC39!).

https://v3.vuejs.org/guide/list.html

The following is valid Vue.js code:

<p v-for="x of {a: 1, b: 2, c: 3}">{{x}}</p>
<p v-for="x in {a: 1, b: 2, c: 3}">{{x}}</p>
  
<p v-for="x of [1, 2, 3]">{{x}}</p>
<p v-for="x in [1, 2, 3]">{{x}}</p>

All of these will print out 1, 2, 3.

In plain JavaScript, however, there is a difference between for..of and for..in.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

The important difference is that for..of will iterate over iterable objects, where for..in will iterate over enumerable properties.

for (const x of {a: 1, b: 2, c: 3}) {console.log(x);} // TypeError ... is not iterable
for (const x in {a: 1, b: 2, c: 3}) {console.log(x);} // Prints a b c

for (const x of [1, 2, 3]) {console.log(x);} // Prints 1 2 3
for (const x in [1, 2, 3]) {console.log(x);} // Prints 0 1 2 (the indexes)

As you can see, they behave very differently.

Even what might look like the same code (for..in {a: 1, b: 2, c: 3}) will yield different results in Vue.js and plain JavaScript, one will print 1, 2, 3, the other a, b, c.

Related