6. Conditional rendering

V-if basic use

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>hello vue</title>
  <! Vue library -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>const app = Vue.createApp({ data() { return { message: "Hello World!" , show: true}}, // We use both v-if and v-show to implement conditional rendering template: '<div v-if='show'>
            {{ message }}
        </div>
        <div v-show='show'>
            {{ message }}
        </div>`}); const vm = app.mount('#root');</script>

</html>
Copy the code

Show is true

When show is false

Usage scenarios

V-if: used on labels that do not adjust their display status very often;

V-show: used to frequently adjust the display status on the label;

Use v – else

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>hello vue</title>
  <! Vue library -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>const app = Vue.createApp({ data() { return { message: "Hello World!" , msg: 'Hello V-ELSE! ', show: false}}, // We use both v-if and v-show to implement conditional rendering template: '<div v-if='show'>
            {{ message }}
        </div>
        <div v-else>
            {{ msg }}
        </div>
        <div v-show='show'>
            {{ message }}
        </div>`}); const vm = app.mount('#root');</script>

</html>
Copy the code

The results

Using v – else – the if

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>hello vue</title>
  <! Vue library -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>const app = Vue.createApp({ data() { return { message: "Hello World!" , msg: 'Hello V-ELSE! ', msg2: 'HELLO v-else -IF', show: false, show2: true}}, // We use v-if and v-show to implement conditional rendering template: '<div v-if='show'>
            {{ message }}
        </div>
        <div v-else-if="show2">
            {{ msg2 }}
        </div>
        <div v-else>
            {{ msg }}
        </div>
        <div v-show='show'>
            {{ message }}
        </div>`}); const vm = app.mount('#root');</script>

</html>
Copy the code

The results