Home  >  Article  >  Web Front-end  >  How to understand conditional rendering in Vue.js? (code example)

How to understand conditional rendering in Vue.js? (code example)

藏色散人
藏色散人Original
2019-03-29 14:30:082772browse

In this tutorial, we will learn to understand conditional rendering in Vue.js.

How to understand conditional rendering in Vue.js? (code example)

What is conditional rendering?

Conditional rendering means that if a certain condition is true, then from Add or remove elements from dom.

In Vue, we need to use the v-if directive to render elements conditionally.

Let’s see an example:

<template>
  <div>
  <!-- v-if="javascript expression" -->
   <h1 v-if="isActive">Hello Vuejs</h1>
   <button @click="isActive= !isActive">点击</button>
  </div>
</template>

<script>

export default{
    data:function(){
        return{
            isActive:false
        }
    }
}
</script>

In the above code, we have added a v-if directive with the attribute isActive , so if the isActive attribute is true, the h1 element is only rendered into dom.

We can also extend the v-else directive after the v-if directive.

 <h1 v-if="isActive">Hello Vuejs</h1>
   <h1 v-else>Hey Vuejs</h1>

If the isActive attribute is true, the first h1 element will be rendered, otherwise the second h1 element will be # rendered ##dom中.

We can also extend this further using the

v-else-if block.

<h1 v-if="isActive">Hello Vuejs</h1>
   <h1 v-else-if="isActive && a.length===0">You&#39;re vuejs</h1>
   <h1 v-else>Hey Vuejs</h1>

In

JavaScript, the v-else-if directive works similarly to the else-if block.

Note: A

v-else element must be immediately followed by a v-if element or a v-if-else element, otherwise it will not work Identify it.

How to render multiple elements conditionally?

Sometimes we have to render multiple elements conditionally, in this case we need to combine the elements in Together.

<template>
  <div v-if="available">
    <h1>Items are available</h1>
    <p>More items in the stock</p>
  </div>
  <div v-else>
    <h1>Items are not available</h1>
    <p>Out of stock</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      available: true
    };
  }
};
</script>

Here we group multiple elements in

div tags.

How to understand conditional rendering in Vue.js? (code example)

Related recommendations: "

javascript tutorial"

This article is about the detailed explanation of conditional rendering in Vue.js. I hope it will help Friends in need help!

The above is the detailed content of How to understand conditional rendering in Vue.js? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn