Home> Web Front-end> Vue.js> body text

Detailed explanation of Vue rendering list command: v-for

青灯夜游
Release: 2022-08-10 17:23:33
forward
1785 people have browsed it

Detailed explanation of Vue rendering list command: v-for

In the previousarticle, we learned how to passv-ifandv-showin 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-forinstruction is provided torender the list. (Learning video sharing:vue video tutorial)

The role of v-for


v-forCan render elements or template blocks multiple times based on source data. This instruction must use specific syntaxalias in expressionto provide an alias for the currently traversed element:

{{ alias }}
Copy after login

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 }}
Copy after login

We can also replaceinwithofas delimiter because it is the closest syntax to JavaScript iterators. The default behavior of

v-forattempts 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 }}
Copy after login

Next, let’s look at some usage scenarios ofv-for.

An arrayv-for


Use thev-forcommand to edit the array option list render. Thev-forinstruction requires special syntax in the form ofitem in items,itemsis the source data array,itemis the array element iteration Alias. Let’s look at a simple example:

 
  • {{ item }}
// JavaScript var app = new Vue({ el: '#app', data: { items: [1, 34, 89, 92, 45, 76, 33] } })
Copy after login

At this time, eachitemof the arrayitemsis 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 arrayitemsthroughv-forCome out and put it inli. In addition, you can also traverse eachindexof the array. Based on the above code, let's modify the template:

  • index-{{ index }}: {{ item }}
Copy after login

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-foris written on that element.

We can already usev-forto 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 thecomputedattribute 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] } })
Copy after login

In order not to pollute the source data in Vue, you need to re-declare an object incomputed, such as declaring asortItemsobject:

var app = new Vue({ el: '#app', computed: { sortItems: function() { return this.items.sort() } }, data: { items: [1, 34, 89, 92, 45, 76, 3, 12] } })
Copy after login

At this time, our The template also needs to be modified accordingly:

  • {{ item }}
Copy after login

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 }
Copy after login

Make a corresponding modification to the code incomputed:

computed: { sortItems: function() { return this.items.sort(sortNumber) } }
Copy after login

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 } ] }
Copy after login

We change the template to:

  • {{ objItem.firstName }} {{objItem.lastName}} is {{ objItem.age}} years old!
  • Copy after login

    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)
    Copy after login

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

    app.items.splice(newLength)
    Copy after login

    对象的v-for


    v-for除了可以使用在数组上之外还可以应用在对象上。

     
    • {{ value }}
    // JavaScript obj: { firstName: 'Airen', lastName: 'Liao', age: 30 }
    Copy after login

    使用v-for可以把obj的每个key对应的value值遍历出来,并且填到对应的li元素中。效果如下:

    你也可以给对象的key遍历出来:

    • {{ key }}: {{ value }}
    Copy after login

    效果如下:

    同样,也可以类似数组一样,可以把index索引做为第三个参数:

    • {{ index }}. {{ key }}: {{ value }}
    Copy after login

    前面提到过,数组可以变异,但对于对象而言,Vue不能检测对象属性的添加或删除。这主要也是由于JavaScript的限制。不过在Vue中,对于已经创建好的实例,可以使用Vue.set(object, key, value)方法向嵌套对象添加响应式属性。例如:

    var app = new Vue({ data: { obj: { name: 'Airen' } } })
    Copy after login

    可以使用类似下面的方式,给obj对象添加一个新的属性age

    Vue.set(app.obj, 'age', 27)
    Copy after login

    回到我们的示例中给数据源中的obj添加一个'from'key,而且其对应的value值为'江西'

    除了Vue.set()之外,还可以使用app.$set实例方法,它其实就是Vue.set的别名:

    mounted(){ this.$set(this.obj, '职位', '码农') }
    Copy after login

    这里用到了Vue中的mounted(),和computed一样,也不知道他在Vue中的作用,同样放到后面来。我们总是会搞明白的。

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

    Object.assign(this.obj, { age: 27, favoriteColor: 'Vue Green' })
    Copy after login

    应该这样做:

    this.obj = Object.assign({}, this.obj, { age: 27, favoriteColor: 'Vue Green' })
    Copy after login

    一段取值范围的v-for


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

    • {{ n }}
    Copy after login

    结果如下:

    v-for和 一个