Vue Basic Tutorial: Conditional Rendering and List Rendering

Vue Basic Tutorial: Conditional Rendering and List Rendering

Preface

What is conditional rendering? There will be many such application scenarios on our pages. For example, if we are going to launch an event today, this event page will only be valid today. At 24:00 in the evening or at 0:01 tomorrow morning, this page must be taken down and the picture must be hidden. If we arrange an operation and maintenance brother to manually change the HTML, he will go crazy. In fact, there is a very simple way here, which is conditional rendering. That is, we judge the condition at 0 o'clock. If the condition reaches a time point such as 24 o'clock or 0 o'clock, then hide it. This is a conditional rendering.

What is list rendering? This is the most common one. For example, if there are many elements and pictures on the page, and a news website loads 20 articles at a time, if you write HTML by hand, then the people on the news website don't have to work and can just type HTML code every day. There will be a loop statement here, similar to the for loop in our C language code, which allows us to construct and generate the elements of this page. This is list rendering. 1 v-if and v-show

1.1 Function

Both are used to control the display and hiding of elements

1.2 How to control the visibility of elements

v-if controls the creation and destruction of elements on the virtual DOM tree. Vue's response system updates the actual DOM based on the virtual DOM tree, thereby indirectly controlling the visibility of elements on the actual DOM.

v-show hides the element by adding the style display:none to the element

1.3 Initial Rendering Comparison

v-if is lazy. If the initial rendering condition is false, nothing will be done. Only when the condition is true will compilation begin.

v-show Regardless of the initial rendering conditions, the element is always compiled and retained, and then switched by CSS based on the conditions

1.4 Switching consumption comparison

If you frequently switch between display and hiding, v-if will frequently create and destroy elements, while v-show only switches styles.

Therefore, the switching cost of v-if is higher

1.5 Comparison of usage scenarios

If the display and hiding of an element is determined at the beginning and will not change, use v-if

If the element needs to be frequently switched, use v-show

1.6 Others

  • v-if can be used with template, but v-show cannot
  • v-if can be used with v-else, v-show has no special syntax

2 v-if and v-for

2.1 Why v-if and v-for cannot be used at the same time

Why can't I use v-if and v-for on the same element at the same time?

When Vue processes instructions, v-for has a higher priority than v-if, so this template:

<ul>
  <li v-for="item in list" v-if="item.isActive" :key="item.id">
    {{item.name}}
  </li>
</ul>

The following operations will be performed:

this.list.map(function(item) {
  if (item.isActive) {
    return item.name
  }
})

We have to traverse the entire list every time we re-render, even if there are few items with isActive set to true, which will result in a huge waste of performance, so both cannot be used on the same element at the same time.

2.2 Solution of using v-if and v-for together

1. If you want to control the visibility of the entire list, you can move v-if to the container element, for example:

<body>
  <div id="example">
    <ul v-if="listShow">
      <li v-for="item in activeItems" :key="item.id">{{item.name}}</li>
    </ul>
  </div>
</body>
<script>
  const vm = new Vue({
    el: "#example",
    data: {
      list: [
        { id: 1, name: "Luffy", isActive: true },
        { id: 2, name: "Sauron", isActive: false },
        { id: 3, name: "Sanji", isActive: true },
      ],
      listShow: false,
    }
  });
</script>

2. If you want to filter the items in the list, you can use computed properties to return the filtered list, for example:

<body>
  <div id="example">
    <ul>
      <li v-for="item in activeItems" :key="item.id">{{item.name}}</li>
    </ul>
  </div>
</body>
<script>
  const vm = new Vue({
    el: "#example",
    data: {
      list: [
        { id: 1, name: "Luffy", isActive: true },
        { id: 2, name: "Sauron", isActive: false },
        { id: 3, name: "Sanji", isActive: true },
      ],
    },
    computed: {
      activeItems: function () {
        return this.list.filter((item) => item.isActive);
      },
    },
  });
</script>

3 What is the use of list rendering key

When using v-for for list rendering, you must add a key attribute to the element, and this key must be a unique identifier

<ul>
 <li v-for="item in list" :key="item.id">{{item.name}}</li>
</ul>

We know that when Vue updates an element, it does not directly operate the real DOM (rendering the real DOM is very expensive), but generates a new virtual DOM based on the new data, then compares the new and old virtual DOMs, and performs DOM operations based on the comparison results to update the view.

When rendering a list, if there is a key attribute, since it is a unique identifier, there is no need to perform an in-depth comparison when comparing two new and old nodes if the keys are different.

Why can't we use index as key? Because the index is unstable and mutable, for example, deleting the first element of the list will cause the index of the subsequent elements to change, which will cause the key to change. At this time, when Vue compares the new and old nodes, if it encounters a node with the same key, it will perform an in-depth comparison. If it finds that the node content has changed, it will create a new real DOM to replace the original real DOM. The operation that originally only needed to delete the first element in the real DOM will become to create and replace all subsequent real DOMs, resulting in a huge waste of performance.

Summarize

This is the end of this article about Vue Basic Tutorial - Conditional Rendering and List Rendering. For more related Vue conditional rendering and list rendering content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • In-depth understanding of Vue's conditional rendering and list rendering
  • A brief analysis of conditional rendering instructions in Vue.js
  • Vue conditional rendering v-if and v-show
  • Detailed explanation of Vue's list rendering
  • v-for directive in vue completes list rendering
  • Detailed explanation of rendering, sorting and filtering of Vue lists
  • Vue conditional rendering and list rendering

<<:  Introduction to the use of http-equiv attribute in meta tag

>>:  Reasons why MySQL queries are slow

Recommend

Getting Started: A brief introduction to HTML's basic tags and attributes

HTML is made up of tags and attributes, which are...

Why is there this in JS?

Table of contents 1. Demand 2. Solution 3. The fi...

Vue login function implementation

Table of contents Written in front Login Overview...

Detailed explanation of the use of Vue3 state management

Table of contents background Provide / Inject Ext...

Why can't I see the access interface for Docker Tomcat?

Question: Is the origin server unable to find a r...

How to change the color of the entire row (tr) when the mouse stops in HTML

Use pure CSS to change the background color of a ...

Experience in designing a layered interface in web design

Many netizens often ask why their websites always ...

CSS pixels and solutions to different mobile screen adaptation issues

Pixel Resolution What we usually call monitor res...

Execution context and execution stack example explanation in JavaScript

JavaScript - Principles Series In daily developme...

mysql implements the operation of setting multiple primary keys

User table, ID number must be unique, mobile phon...

Use and analysis of Mysql Explain command

The mysql explain command is used to show how MyS...

About VUE's compilation scope and slot scope slot issues

What are slots? The slot directive is v-slot, whi...