Home > Web Front-end > JS Tutorial > Detailed introduction to list rendering in vuejs

Detailed introduction to list rendering in vuejs

不言
Release: 2018-08-14 16:47:38
Original
2829 people have browsed it

This article brings you a detailed introduction to list rendering in vuejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Use v-for to correspond an array to a set of elements

We use the v-for instruction to render based on the option list of a set of arrays. The v-for directive requires special syntax of the form item in items, where items is the source data array and item is an alias for iterating over the array elements.

<ul id="example-1">
<li v-for="item in items">
{{ item.message }}
</li>
</ul>
var example1 = new Vue({
el: &#39;#example-1&#39;,
data: {
items: [
{ message: &#39;Foo&#39; },
{ message: &#39;Bar&#39; }
]
}
})
Copy after login

In the v-for block, we have full access to the parent scope properties. v-for also supports an optional second parameter that is the index of the current item.

<ul id="example-2">
<li v-for="(item, index) in items">
{{ parentMessage }} - {{ index }} - {{ item.message }}
</li>
</ul>
var example2 = new Vue({
el: &#39;#example-2&#39;,
data: {
parentMessage: &#39;Parent&#39;,
items: [
{ message: &#39;Foo&#39; },
{ message: &#39;Bar&#39; }
]
}
})
Copy after login

You can also use of instead of in as the separator, because it is the syntax closest to javascript iterators

<p v-for="item of items"></p>
Copy after login

v-for for an object

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

<ul id="v-for-object" class="demo">
<li v-for="value in object">
{{ value }}
</li>
</ul>
new Vue({
el: &#39;#v-for-object&#39;,
data: {
object: {
firstName: &#39;John&#39;,
lastName: &#39;Doe&#39;,
age: 30
}
}
})
Copy after login

You can also provide the second parameter as the key name

<p v-for="(value, key) in object">
{{ key }}: {{ value }}
</p>
Copy after login

The third parameter is the index:

<p v-for="(value, key, index) in object">
{{ index }}. {{ key }}: {{ value }}
</p>
Copy after login

When traversing the object, it is Traverse according to the results of Object.key(), but there is no guarantee that its results are consistent under different javascript engines.

key

When vue.js is being updated using v-for When rendering a list of elements, it defaults to the "in-place reuse" strategy. If the order of data items is changed. Vue will not move the DOM elements to match the order of the data items, but will simply reuse each element there and make sure it displays each element rendered at a specific index. This is similar to track-by="$index" of vue1.x.

This default mode is efficient, but is only suitable for list rendering output that does not rely on subcomponent state or temporary DOM state (for example: form input values).

In order to give Vue a hint so that it can track the identity of each node and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item. The ideal key value is a unique id for each item. This special attribute is equivalent to vue1.x's track-by, but it works like a property, so you need to use v-bind to bind dynamically value.

<p v-for="item in items" :key="item.id">
<!-- 内容 -->
</p>
Copy after login

It is recommended to provide key when using v-for as much as possible, unless traversing the output dom content is very simple or can be relied on Default behavior to gain performance improvements.

Because it is a general mechanism for Vue to identify nodes, key is not specifically related to v-for, key also has other uses,

Array update detection

Compiled methods

#vue contains compiled methods that always observe the array, so they will also trigger view updates.

* push()————Into the array

* pop()———— Out of the array

* shift()————

* unshift()

* splice()——Split the array

* sort() ————Sort the array

* reverse()————Flip the array

Replace the array

mutation method, which will change the original array called by these methods. In contrast, there are also non-mutational methods. For example: filter(), concat() and slice().

These do not change the original array, but always return a new array. When using the non-mutation method, you can replace the old array with a new array

##

example1.items = example1.items.filter(function (item) {
return item.message.match(/Foo/)
})
Copy after login

You may think that this will cause vue to discard the existing dom and re-renders the entire list. Fortunately, this is not the case. Vue has implemented some smart and heuristic methods in order to maximize the reuse of DOM elements, so replacing the original array with an array containing the same elements is a very efficient operation.

Notes

Due to JavaScript limitations, vue cannot detect the following changed arrays

1. When you use an index to directly set an item, for example: vm.items[ indexOfItem] = newValue

2. When you modify the length of the array, for example: vm.items.length = newLength

var vm = new Vue({
data: {
items: [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
}
})
vm.items[1] = &#39;x&#39; // 不是响应性的
vm.items.length = 2 // 不是响应性的
Copy after login

In order to solve the first type of problem, the following two methods can achieve the same effect as vm.items[indexOfItem] = newValue, and will also trigger status update

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)
Copy after login

你也可以使用vm.$set实例方法,该方法是全局方法vue.set的一个别名

vm.$set(vm.items, indexOfItem, newValue)
Copy after login

为了解决第二类问题,你可以使用splice

vm.items.splice(newLength)
Copy after login

splice()方法向/从数组添加/删除项目,然后返回被删除的项目

arrayObject.splice(index,howmany,item1,.....,itemX)
Copy after login

index

必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。

howmany

必需。要删除的项目数量。如果设置为 0,则不会删除项目。

item1, ..., itemX

可选。向数组添加的新项目。

对象更改检测注意事项

还是由于javascript的限制,vue不能检测对象属性的添加或删除

var vm = new Vue({
data: {
a: 1
}
})
// `vm.a` 现在是响应式的
 
vm.b = 2
// `vm.b` 不是响应式
Copy after login

对于已经创建的实例,vue不能动态添加跟级别的响应式属性。但是,可以使用 Vue.set(object, key, value)方法向嵌套对象添加响应式属性。

var vm = new Vue({
data: {
userProfile: {
name: &#39;Anika&#39;
}
}
})
Copy after login

你可以添加一个age属性到嵌套的userProfile对象:

Vue.set(vm.userProfile, &#39;age&#39;, 27)
Copy after login

你还可以使用vm.$set实例方法,他只是全局vue.set的别名

vm.$set(vm.userProfile, &#39;age&#39;, 27)
Copy after login

有事你可能需要为已有对象赋予多个新属性,比如使用 Object.assign() 或 _.extend()。在这种情况下,你应该用两个对象的属性创建一个新的对象。所以,如果你想添加新的响应式属性,不要像这样:

Object.assign(vm.userProfile, {
age: 27,
favoriteColor: &#39;Vue Green&#39;
})
你应该这样:
vm.userProfile = Object.assign({}, vm.userProfile, {
age: 27,
favoriteColor: &#39;Vue Green&#39;
})
Copy after login

显示过滤/排序结果

有事,我们想要显示一个数组的过滤或排序副本,而不实际改变 或重置原始数据。在这种情况下,可以创建返回过滤或排序 数组的计算属性。

<li v-for="n in evenNumbers">{{ n }}</li>
data: {
  numbers: [ 1, 2, 3, 4, 5 ]
},
computed: {
  evenNumbers: function () {
    return this.numbers.filter(function (number) {
      return number % 2 === 0
    })
  }
}
Copy after login

在计算属性不使用的情况下,(例如,在嵌套v-for循环中)你可以使用method方法。

data: {
numbers: [ 1, 2, 3, 4, 5 ]
},
methods: {
even: function (numbers) {
return numbers.filter(function (number) {
return number % 2 === 0
})
}
}
Copy after login

一段取值范围的v-for

v-for也可以取整数。在这种情况下 ,它将重复多刺激模板。

<p>
<span v-for="n in 10">{{ n }} </span>
</p>
Copy after login

v-for on a