Vue conditional rendering v-if and v-show

Vue conditional rendering v-if and v-show

1. v-if

In templates, you can render conditionally. The conditions are implemented by combining v-if , v-else-if and v-else .

The sample code is as follows:

<div id="app">
    <p v-if="weather == 'sun'">Let's go to the park today! </p>
    <p v-else-if="weather == 'rain'">Go to the movies today! </p>
    <p v-else>Not going anywhere today! </p>
</div>
<script>
    let vm = new Vue({
        el: "#app",
        data: {
            weather: 'sun'
        }
    });
</script>
 

2. Use v-if on <template>

Sometimes we want to load multiple html elements in one condition, then we can do it on template element.

The sample code is as follows:

<div id="app">
    <template v-if="age<18">
        <p>How many points do you have in math? </p>
        <p>How many points do you have in English? </p>
    </template>
    <template v-else-if="age>=18 && age<25">
        <p>Are you married? </p>
        <p>Have you taken the postgraduate entrance examination? </p>
    </template>
    <template v-else>
        <p>Did you get a pay raise? </p>
        <p>How much is the salary? </p>
    </template>
</div>
<script>
    let vm = new Vue({
        el: "#app",
        data: {
            age: 24
        }
    });
</script>
 

3. Use keys to manage reusable elements

In addition, in the template, Vue will try to reuse existing elements instead of re-rendering, which can be more efficient.

If we allow users to switch between different login methods:

<div id="app">
  <template v-if="loginType === 'username'">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" placeholder="username">
  </template>
  <template v-else>
    <label for="email">Email</label>
    <input type="text" id="email" name="email" placeholder="Email">
  </template>
  <div>
    <button @click="changeLoginType">Switch login type</button>
  </div>
</div>
<script>
  const app = new Vue({
    el: "#app",
    data: {
      loginType: "username"
    },
    methods: {
      changeLoginType(){
        // If the type is username, switch to email, otherwise this.loginType = this.loginType==="username"?"email":"username";
      }
    }
  })
</script>

Next, let’s look at the effect diagram:

There will be a problem here. If I enter the information in the username input box and switch to the mailbox, the previous information will still be retained. This is definitely not in line with the requirements. If we want html element to be re-rendered every time it is switched, we can add a unique key attribute to the element that needs to be re-rendered. It is recommended to use an integer or string type for key attribute.

The sample code is as follows:

<div id="app">
  <template v-if="loginType === 'username'">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" placeholder="username" key="username">
  </template>
  <template v-else>
    <label for="email">Email</label>
    <input type="text" id="email" name="email" placeholder="Email" key="email">
  </template>
  <div>
    <button @click="changeLoginType">Switch login type</button>
  </div>
</div>

We can see that when the user name 123 is switched to the email mode, 123 in the input box disappears.

Note: <label> elements can still be effectively reused since they do not have a key attribute added to them.

4. v-show

Another option for conditionally showing elements is the v-show directive. The usage is roughly the same:

<h1 v-show="ok">Hello!</h1>


The difference is that elements with v-show are always rendered and remain in DOM . v-show simply toggles CSS property display of an element.

Note: v-show does not support the <template> element, nor does it support v-else.

4.1 v-if vs. v-show

v-if is “true” conditional rendering, as it ensures that event listeners and child components within the conditional block are properly destroyed and rebuilt during the toggle.

v-if is also lazy: if the condition is false on initial render, nothing is done - the conditional block is not rendered until the condition becomes true for the first time.

In comparison, v-show is much simpler - the element is always rendered regardless of the initial conditions, and is simply toggled based on CSS .

Generally speaking, v-if has higher switching cost, while v-show has higher initial rendering cost. Therefore, if you need to switch very frequently, it is better to use v-show ; if the condition rarely changes during runtime, it is better to use v-if .

This is the end of this article about vue conditional rendering v-if and v-show. For more related vue conditional 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 Basic Tutorial: Conditional Rendering and List Rendering
  • 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

<<:  Why Nginx is better than Apache

>>:  Detailed explanation of DIV+CSS naming rules can help achieve SEO optimization

Recommend

MySQL multi-master and one-slave data backup method tutorial

Overview Operations on any one database are autom...

How to Apply for Web Design Jobs

<br />Hello everyone! It’s my honor to chat ...

Detailed explanation of how to use join to optimize SQL in MySQL

0. Prepare relevant tables for the following test...

Use JS to operate files (FileReader reads --node's fs)

Table of contents JS reads file FileReader docume...

HTML version declaration DOCTYPE tag

When we open the source code of a regular website...

Solution to the paging error problem of MySQL one-to-many association query

The query data in the xml price inquiry contains ...

jQuery plugin to implement floating menu

Learn a jQuery plugin every day - floating menu, ...

Solve the problem of installing Theano on Ubuntu 19

Solution: Directly in the directory where you dow...

5 Reasons Why Responsive Web Design Isn’t Worth It

This article is from Tom Ewer's Managewp blog,...

Solve the black screen problem after VMware installs Linux system and starts

1. Installation environment 1. HUAWEI mate x cpu ...

Linux uses suid vim.basic file to achieve privilege escalation

Reproduce on Kali First set suid permissions for ...

About WSL configuration and modification issues in Docker

https://docs.microsoft.com/en-us/windows/wsl/wsl-...

Automatically log out inactive users after login timeout in Linux

Method 1: Modify the .bashrc or .bash_profile fil...

Detailed explanation of anonymous slots and named slots in Vue

Table of contents 1. Anonymous slots 2. Named slo...