List Rendering

Mapping an Array to Elements with v-for

We can use the v-for directive to render a list of items based on an array. The v-for directive requires a special syntax in the form of item in items, where items is the source data array and item is an alias for the array element being iterated on:

  1. <ul id="array-rendering">
  2. <li v-for="item in items">
  3. {{ item.message }}
  4. </li>
  5. </ul>
  1. Vue.createApp({
  2. data() {
  3. return {
  4. items: [{ message: 'Foo' }, { message: 'Bar' }]
  5. }
  6. }
  7. }).mount('#array-rendering')

Result:

List Rendering - 图1

See the Pen v-for with Array by Vue (@Vue) on CodePen.

Inside v-for blocks we have full access to parent scope properties. v-for also supports an optional second argument for the index of the current item.

  1. <ul id="array-with-index">
  2. <li v-for="(item, index) in items">
  3. {{ parentMessage }} - {{ index }} - {{ item.message }}
  4. </li>
  5. </ul>
  1. Vue.createApp({
  2. data() {
  3. return {
  4. parentMessage: 'Parent',
  5. items: [{ message: 'Foo' }, { message: 'Bar' }]
  6. }
  7. }
  8. }).mount('#array-with-index')

Result:

See the Pen v-for with Array and index by Vue (@Vue) on CodePen.

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

  1. <div v-for="item of items"></div>

v-for with an Object

You can also use v-for to iterate through the properties of an object.

  1. <ul id="v-for-object" class="demo">
  2. <li v-for="value in myObject">
  3. {{ value }}
  4. </li>
  5. </ul>
  1. Vue.createApp({
  2. data() {
  3. return {
  4. myObject: {
  5. title: 'How to do lists in Vue',
  6. author: 'Jane Doe',
  7. publishedAt: '2016-04-10'
  8. }
  9. }
  10. }
  11. }).mount('#v-for-object')

Result:

See the Pen v-for with Object by Vue (@Vue) on CodePen.

You can also provide a second argument for the property’s name (a.k.a. key):

  1. <li v-for="(value, name) in myObject">
  2. {{ name }}: {{ value }}
  3. </li>

See the Pen v-for with Object and key by Vue (@Vue) on CodePen.

And another for the index:

  1. <li v-for="(value, name, index) in myObject">
  2. {{ index }}. {{ name }}: {{ value }}
  3. </li>

See the Pen v-for with Object key and index by Vue (@Vue) on CodePen.

Note

When iterating over an object, the order is based on the enumeration order of Object.keys(), which isn’t guaranteed to be consistent across JavaScript engine implementations.

Maintaining State

When Vue is updating a list of elements rendered with v-for, by default it uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will patch each element in-place and make sure it reflects what should be rendered at that particular index.

This default mode is efficient, but only suitable when your list render output does not rely on child component state or temporary DOM state (e.g. form input values).

To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item:

  1. <div v-for="item in items" :key="item.id">
  2. <!-- content -->
  3. </div>

It is recommended to provide a key attribute with v-for whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.

Since it’s a generic mechanism for Vue to identify nodes, the key also has other uses that are not specifically tied to v-for, as we will see later in the guide.

Note

Don’t use non-primitive values like objects and arrays as v-for keys. Use string or numeric values instead.

For detailed usage of the key attribute, please see the key API documentation.

Array Change Detection

Mutation Methods

Vue wraps an observed array’s mutation methods so they will also trigger view updates. The wrapped methods are:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

You can open the console and play with the previous examples’ items array by calling their mutation methods. For example: example1.items.push({ message: 'Baz' }).

Replacing an Array

Mutation methods, as the name suggests, mutate the original array they are called on. In comparison, there are also non-mutating methods, e.g. filter(), concat() and slice(), which do not mutate the original array but always return a new array. When working with non-mutating methods, you can replace the old array with the new one:

  1. example1.items = example1.items.filter(item => return item.message.match(/Foo/))

You might think this will cause Vue to throw away the existing DOM and re-render the entire list - luckily, that is not the case. Vue implements some smart heuristics to maximize DOM element reuse, so replacing an array with another array containing overlapping objects is a very efficient operation.

Displaying Filtered/Sorted Results

Sometimes we want to display a filtered or sorted version of an array without actually mutating or resetting the original data. In this case, you can create a computed property that returns the filtered or sorted array.

For example:

  1. <li v-for="n in evenNumbers">{{ n }}</li>
  1. data() {
  2. return {
  3. numbers: [ 1, 2, 3, 4, 5 ]
  4. }
  5. },
  6. computed: {
  7. evenNumbers() {
  8. return this.numbers.filter(number => number % 2 === 0)
  9. }
  10. }

In situations where computed properties are not feasible (e.g. inside nested v-for loops), you can use a method:

  1. <ul v-for="numbers in sets">
  2. <li v-for="n in even(numbers)">{{ n }}</li>
  3. </ul>
  1. data() {
  2. return {
  3. sets: [[ 1, 2, 3, 4, 5 ], [6, 7, 8, 9, 10]]
  4. }
  5. },
  6. methods: {
  7. even(numbers) {
  8. return numbers.filter(number => number % 2 === 0)
  9. }
  10. }

v-for with a Range

v-for can also take an integer. In this case it will repeat the template that many times.

  1. <div id="range" class="demo">
  2. <span v-for="n in 10">{{ n }} </span>
  3. </div>

Result:

See the Pen v-for with a range by Vue (@Vue) on CodePen.

v-for on a