Guide
Essentials
- Installation
- Introduction
- The Vue Instance
- Template Syntax
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Event Handling
- Form Input Bindings
- Components Basics
Components In-Depth
- Component Registration
- Props
- Custom Events
- Slots
- Dynamic & Async Components
- Handling Edge Cases
Transitions & Animation
- Enter/Leave & List Transitions
- State Transitions
Reusability & Composition
- Mixins
- Custom Directives
- Render Functions & JSX
- Plugins
- Filters
Tooling
- Single File Components
- Testing
- TypeScript Support
- Production Deployment
Scaling Up
- Routing
- State Management
- Server-Side Rendering
- Security
Internals
- Reactivity in Depth
Migrating
- Migration from Vue 1.x
- Migration from Vue Router 0.7.x
- Migration from Vuex 0.6.x to 1.0
- Migration to Vue 2.7
Meta
- Comparison with Other Frameworks
- Join the Vue.js Community!
- Meet the Team
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:
|
|
Result:
- {{item.message}}
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.
|
|
Result:
- {{ parentMessage }} - {{ index }} - {{ item.message }}
You can also use of as the delimiter instead of in, so that it is closer to JavaScript’s syntax for iterators:
|
v-for with an Object
You can also use v-for to iterate through the properties of an object.
|
|
Result:
- {{ value }}
You can also provide a second argument for the property’s name (a.k.a. key):
|
And another for the index:
|
When iterating over an object, the order is based on the enumeration order of Object.keys(), which is not 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 is similar to the behavior of track-by="$index" in Vue 1.x.
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:
|
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.
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:
|
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.
Caveats
Due to limitations in JavaScript, there are types of changes that Vue cannot detect with arrays and objects. These are discussed in the reactivity section.
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:
|
|
In situations where computed properties are not feasible (e.g. inside nested v-for loops), you can use a method:
|
|
v-for with a Range
v-for can also take an integer. In this case it will repeat the template that many times.
|
Result:
v-for on a <template>
Similar to template v-if, you can also use a <template> tag with v-for to render a block of multiple elements. For example:
|
v-for with v-if
Note that it’s not recommended to use v-if and v-for together. Refer to style guide for details.
When they exist on the same node, v-for has a higher priority than v-if. That means the v-if will be run on each iteration of the loop separately. This can be useful when you want to render nodes for only some items, like below:
|
The above only renders the todos that are not complete.
If instead, your intent is to conditionally skip execution of the loop, you can place the v-if on a wrapper element (or <template>). For example:
|
v-for with a Component
This section assumes knowledge of Components. Feel free to skip it and come back later.
You can directly use v-for on a custom component, like any normal element:
|
In 2.2.0+, when using
v-forwith a component, akeyis now required.
However, this won’t automatically pass any data to the component, because components have isolated scopes of their own. In order to pass the iterated data into the component, we should also use props:
|
The reason for not automatically injecting item into the component is because that makes the component tightly coupled to how v-for works. Being explicit about where its data comes from makes the component reusable in other situations.
Here’s a complete example of a simple todo list:
|
Note the is="todo-item" attribute. This is necessary in DOM templates, because only an <li> element is valid inside a <ul>. It does the same thing as <todo-item>, but works around a potential browser parsing error. See DOM Template Parsing Caveats to learn more.
|