List Rendering

您所在的位置:网站首页 篮球训练ppt List Rendering

List Rendering

#List Rendering | 来源: 网络整理| 查看: 265

List Rendering Learn how to render list with a free Vue School lesson 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:

{{ item.message }} var example1 = new Vue({ el: '#example-1', data: { items: [ { message: 'Foo' }, { message: 'Bar' } ] }})

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.

{{ parentMessage }} - {{ index }} - {{ item.message }} var example2 = new Vue({ el: '#example-2', data: { parentMessage: 'Parent', items: [ { message: 'Foo' }, { message: 'Bar' } ] }})

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.

{{ value }} new Vue({ el: '#v-for-object', data: { object: { title: 'How to do lists in Vue', author: 'Jane Doe', publishedAt: '2016-04-10' } }})

Result:

{{ value }}

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

{{ name }}: {{ value }} {{ name }}: {{ value }}

And another for the index:

{{ index }}. {{ name }}: {{ value }} {{ index }}. {{ name }}: {{ value }}

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 DetectionMutation 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:

example1.items = example1.items.filter(function (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.

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:

{{ n }} data: { numbers: [ 1, 2, 3, 4, 5 ]},computed: { evenNumbers: function () { return this.numbers.filter(function (number) { return number % 2 === 0 }) }}

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

{{ n }} data: { sets: [[ 1, 2, 3, 4, 5 ], [6, 7, 8, 9, 10]]},methods: { even: function (numbers) { return numbers.filter(function (number) { return number % 2 === 0 }) }} v-for with a Range

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

{{ n }}

Result:

{{ n }} v-for on a

Similar to template v-if, you can also use a tag with v-for to render a block of multiple elements. For example:

{{ item.msg }} 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:

{{ todo }}

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 ). For example:

{{ todo }} No todos left! 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-for with a component, a key is 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:

Add a todo Add

Note the is="todo-item" attribute. This is necessary in DOM templates, because only an element is valid inside a . It does the same thing as , but works around a potential browser parsing error. See DOM Template Parsing Caveats to learn more.

Vue.component('todo-item', { template: '\ \ {{ title }}\ Remove\ \ ', props: ['title']})

new Vue({ el: '#todo-list-example', data: { newTodoText: '', todos: [ { id: 1, title: 'Do the dishes', }, { id: 2, title: 'Take out the trash', }, { id: 3, title: 'Mow the lawn' } ], nextTodoId: 4 }, methods: { addNewTodo: function () { this.todos.push({ id: this.nextTodoId++, title: this.newTodoText }) this.newTodoText = '' } }})

← Conditional Rendering Event Handling → Caught a mistake or want to contribute to the documentation? Edit this on GitHub! Deployed on Netlify .


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3