[Vue] Detailed introduction to the use of v-for in Vue

The v-for instruction is a commonly used list rendering instruction in Vue.js, which can easily perform loop rendering based on arrays or objects. The specific usage is as follows:

1. Basic grammar

<div v-for="(item, index) in items">
  {
    
    { index }} - {
    
    { item }}
</div>

Among them, after v-for (item, index) in items, items is the data source that needs to be traversed, item is the value of each element, and index is the index of each element.

2. Traverse objects

<div v-for="(value, key, index) in object">
  {
    
    { index }} - {
    
    { key }}: {
    
    { value }}
</div>

When v-for traverses the object, (value, key, index) in objectvalue is the value of each attribute, key is the key of each attribute, and index is the index of the attribute.

3. Traverse the numbers

<div v-for="n in 10">
  {
    
    { n }}
</div>

When v-for traverses numbers, n in 1010 is the number range that needs to be traversed.

4.v-for key

<div v-for="(item, index) in items" :key="index">
  {
    
    { index }} - {
    
    { item }}
</div>

When using v-for for loop rendering, each element should have a unique key value so that Vue.js can render the list more efficiently . You can:keyspecify the key value by . It is generally recommended to use the unique identifier of the element in the data source as the key value.

5.Combined use of v-for and v-if

<div v-for="(item, index) in items" v-if="item.active">
  {
    
    { index }} - {
    
    { item }}
</div>

When using v-for and v-if in combination, pay attention to the position of v-if. If v-if is placed after v-for, all elements will be rendered first and then filtered based on v-if. If v-if is placed before v-for, only elements that meet the condition will be rendered. If you want to filter data at the same time and reduce rendering overhead, it is recommended to use computed properties or filters instead of v-if.

The above is the basic usage of the v-for instruction, which can be used flexibly according to actual needs.

Guess you like

Origin blog.csdn.net/wenhuakulv2008/article/details/132921657