Home>Article>Web Front-end> Detailed explanation of Vue rendering list command: v-for
In the previousarticle, we learned how to passv-if
andv-show
in Vue Render the required DOM elements or templates based on conditions. In actual projects, we often encounter elements such as lists that render arrays or objects in JSON data. In Vue, av-for
instruction is provided torender the list. (Learning video sharing:vue video tutorial)
The role of v-for
v-for
Can render elements or template blocks multiple times based on source data. This instruction must use specific syntaxalias in expression
to provide an alias for the currently traversed element:
{{ alias }}
Generally, aliases are specified for arrays or objects. In addition, they can also be used for indexes. The value specifies an alias. For objects, you can also specify an alias forvalue
. Common situations are as follows:
{{ item }}{{ item }} {{ index }}
We can also replacein
withof
as delimiter because it is the closest syntax to JavaScript iterators. The default behavior of
v-for
attempts not to change the whole, but to replace elements. To force elements to be reordered, you need to provide a special attribute ofkey
:
{{ item.text }}
Next, let’s look at some usage scenarios ofv-for
.
v-for
Use thev-for
command to edit the array option list render. Thev-for
instruction requires special syntax in the form ofitem in items
,items
is the source data array,item
is the array element iteration Alias. Let’s look at a simple example:
At this time, eachitem
of the arrayitems
is rendered to the correspondingli
. When browsing The effect seen by the processor is as follows:
The above example is to iterate each item of the arrayitems
throughv-for
Come out and put it inli
. In addition, you can also traverse eachindex
of the array. Based on the above code, let's modify the template:
At this time, the index number of the array is also traversed:
From the above display The column is clear, which element (HTML tag) you need to loop, thenv-for
is written on that element.
We can already usev-for
to output each item of the defined array normally. In order to deepen our learning, we add a requirement based on the above example, which is to sort the output array. At this time, we need to use thecomputed
attribute in Vue.
In Vue, we cannot pollute the source data. If we directly sort the source data items through the sort() method, an error will be reported:
var app = new Vue({ el: '#app', computed: { items: function() { return this.items.sort() } }, data: { items: [1, 34, 89, 92, 45, 76, 33] } })
In order not to pollute the source data in Vue, you need to re-declare an object incomputed
, such as declaring asortItems
object:
var app = new Vue({ el: '#app', computed: { sortItems: function() { return this.items.sort() } }, data: { items: [1, 34, 89, 92, 45, 76, 3, 12] } })
At this time, our The template also needs to be modified accordingly:
If nothing else happens, the effect you will see will be like this:
Although there have been changes , but it is not the sorting result we want. Although the result is not what we want, this is not a problem with Vue itself, it is also the same in JavaScript. If we want to truly achieve a sorting effect, we need to add a JavaScript array sorting function:
function sortNumber(a, b) { return a - b }
Make a corresponding modification to the code incomputed
:
computed: { sortItems: function() { return this.items.sort(sortNumber) } }
The output effect of this phase is really a correct sorting effect:
In the above example, what we see is a simple pure For arrays such as numbers, each item in the array can also be an object, for example:
data: { objItems: [ { firstName: 'Jack', lastName: 'Li', age: 34 }, { firstName: 'Airen', lastName: 'Liao', age: 18 } ] }
We change the template to:
The effect we see at this time is as follows:
在JavaScript中,我们有很多数组的方法,可以对数组进行操作,这些方法可以修改一个数组。其实,在Vue中同样包含一组观察数组变异方法,这些方法将会触发元素的重新更新(视图更新),这些方法也是JavaScript中数组中常看到的方法:push()
、pop()
、shift()
、unshift()
、splice()
、sort()
、reverse()
。我们可以在控制台中简单的看一下前面的示例中items
数组调用变异方法的效果:
Vue不但提供了数组变异的方法,还提供了替换数组的方法。变异方法可以通过些方法的调用修改源数据中的数组;除此之外也有对应的非变异方法,比如filter()
、concat()
和slice()
等。这些方法是不会改变源数据中的原始数组,但总是返回一个新数组。当使用这些方法时,可以用新数组替换旧数组。
由于JavaScript的限制,Vue不能检测以下变动的数组:
app.items[indexOfItem] = newValue
app.items.length = newLength
为了解决第一类问题,以下两种方式都可以实现和app.items[indexOfItem = newValue
相同的效果,同时也将触发状态更新:
Vue.set(app.items, indexOfItem, newValue) app.items.splice(indexOfItem, 1, newValue)
为了解决第二类问题,你可以使用splice()
:
app.items.splice(newLength)
v-for
v-for
除了可以使用在数组上之外还可以应用在对象上。
使用v-for
可以把obj
的每个key
对应的value
值遍历出来,并且填到对应的li
元素中。效果如下:
你也可以给对象的key
遍历出来:
效果如下:
同样,也可以类似数组一样,可以把index
索引做为第三个参数:
前面提到过,数组可以变异,但对于对象而言,Vue不能检测对象属性的添加或删除。这主要也是由于JavaScript的限制。不过在Vue中,对于已经创建好的实例,可以使用Vue.set(object, key, value)
方法向嵌套对象添加响应式属性。例如:
var app = new Vue({ data: { obj: { name: 'Airen' } } })
可以使用类似下面的方式,给obj
对象添加一个新的属性age
:
Vue.set(app.obj, 'age', 27)
回到我们的示例中给数据源中的obj
添加一个'from'
的key
,而且其对应的value
值为'江西'
:
除了Vue.set()
之外,还可以使用app.$set
实例方法,它其实就是Vue.set
的别名:
mounted(){ this.$set(this.obj, '职位', '码农') }
这里用到了Vue中的
mounted()
,和computed
一样,也不知道他在Vue中的作用,同样放到后面来。我们总是会搞明白的。
有时候你可能需要为已有对象赋予多个新属性,比如使用Object.assign()
或_.extend()
。在这种情况下,应该用两个对象的属性创建一个新的对象。所以,如果你想添加新的响应式属性,不要像这样:
Object.assign(this.obj, { age: 27, favoriteColor: 'Vue Green' })
应该这样做:
this.obj = Object.assign({}, this.obj, { age: 27, favoriteColor: 'Vue Green' })
v-for
v-for
也可以取整数。在这种情况下,它将重复多次模板:
结果如下:
v-for
和 一个
类似于v-if
,你也可以利用带有v-for
的渲染多个元素,比如:
效果如下:
注意了,v-for
和一起使用的时候,需要把
v-for
写在元素上。另外上面的示例中,咱们还使用了Vue的一些其他特性,但这些特性不是这节内容所要学习的。后面我们会有机会一一介绍的。
v-for
在自定义组件里,也可以像任何普通元素一样用v-for
。
2.2.0+ 的版本里,当在组件中使用
v-for
时,key
现在是必须的。
然而他不能自动传递数据到组件里,因为组件有自己独立的作用域。为了传递迭代数据到组件里,我们要用props
:
不自动注入item
到组件里的原因是,因为这使得组件会与v-for
的运作紧密耦合。在一些情况下,明确数据的来源可以使组件可重用。
来看一个简单的Todo示例:
Vue.component('todoItem', { template:`
这篇文章主要总结了Vue的v-for
指令。通过这个指令,配合数据源中的数组或者对象,我们可以很方便的生成列表。这也常常称为列表渲染。当然配合一些模板,我们可以做出一些特有的功能和效果。比如文章中最后一个Todo 列表,使用v-for
很易实现。
The above is the detailed content of Detailed explanation of Vue rendering list command: v-for. For more information, please follow other related articles on the PHP Chinese website!