Points to note when using v-for/v-if

v-for: Array data can be rendered cyclically. Its syntax is: v-for="item in items", where itemeach array element itemsis the array itself.

v-if: An element can be dynamically rendered or not rendered according to a condition. Its syntax is: v-if="isShow", which isShowis a Boolean value indicating whether to render the element.

<template>
  <div>
    <ul>
      <li v-for="item in items" :key="item.id">{
   
   {item.text}}</li>
    </ul>
    <p v-if="isShow">This is a conditionally rendered element</p>
  </div>
</template>

<script>
export default {
  data () {
    return {
      items: [
        { id: 1, text: 'Item 1' },
        { id: 2, text: 'Item 2' },
        { id: 3, text: 'Item 3' }
      ],
      isShow: true
    }
  }
}
</script>

v-for and v-if do not put on an element

Because the priority of v-for is higher than that of v-if, if they are used together, the loop rendering is performed first, and then v-if is judged

This creates performance issues.

For example, in the following code, use both v-for and v-if on each li element:

<ul>
  <li v-for="item in items" v-if="item.isActive">
    {
    
    {
    
     item.name }}
  </li>
</ul>

This way of writing will cause each li element to be judged and looped, which may increase the amount of processing and reduce performance.

Note:

If the condition appears inside the loop, you can use the computed property to perform a filter first

Using a computed property for one-shot filtering is an effective way to alleviate the problem when the condition occurs in a loop. This is because computed properties are automatically updated when the data changes, rather than being recomputed on every render.

For example, if you use a v-if in a loop to control the display of certain elements, the condition will be recalculated every time you render. In contrast, if you filter using a computed property, it will only be recalculated when the data changes.

Sample code:

// Template
<template>
  <ul>
    <li v-for="item in filteredItems">{
   
   { item.name }}</li>
  </ul>
</template>
// JavaScript
data() {
    
    
    return {
    
    
        items: [
        {
    
     name: 'Item 1', show: true },
        {
    
     name: 'Item 2', show: false },
        {
    
     name: 'Item 3', show: true }
        ]
    }
},
    computed: {
    
    
        filteredItems() {
    
    
        	return this.items.filter(item => item.show)
        }
}

Guess you like

Origin blog.csdn.net/m0_61696809/article/details/129351474