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

Native JavaScript implementation of progress bar

The specific code for JavaScript to implement the...

Tutorial on installing MySQL 5.6 on CentOS 6.5

1. Download the RPM package corresponding to Linu...

Docker container custom hosts network access operation

Adding the extra_hosts keyword in docker-compose....

W3C Tutorial (14): W3C RDF and OWL Activities

RDF and OWL are two important semantic web techno...

Detailed tutorial for installing MySQL 8.0.11 compressed version under win10

After reinstalling my computer recently, I downlo...

Docker Tutorial: Using Containers (Simple Example)

If you’re new to Docker, take a look at some of t...

Docker starts in Exited state

After docker run, the status is always Exited Sol...

Analysis of the principle of centering elements with CSS

It is a very common requirement to set the horizo...

HTML meta viewport attribute description

What is a Viewport Mobile browsers place web page...

Analysis of several situations where MySQL index fails

1. Best left prefix principle - If multiple colum...

JavaScript canvas text clock

This article example shares the specific code of ...

Detailed steps to install xml extension in php under linux

Installing XML extension in PHP Linux 1. Enter th...