美文网首页
【Vue3 从入门到实战 进阶式掌握完整知识体系】006-Vue

【Vue3 从入门到实战 进阶式掌握完整知识体系】006-Vue

作者: 訾博ZiBo | 来源:发表于2021-06-20 15:25 被阅读0次

6、条件渲染

v-if基本使用

<!DOCTYPE html>
<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库 -->
  <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
      }
    },
    // 我们使用 v-if 与 v-show 两种方式来实现条件渲染
    template: `
        <div v-if='show'>
            {{ message }}
        </div>
        <div v-show='show'>
            {{ message }}
        </div>
    `
  });

  const vm = app.mount('#root');
</script>

</html>

show 为 true的时候

image-20210612195130251.png

show 为 false 的时候

image-20210612195336843.png

使用场景

v-if:用在不经常调整显示状态的标签上;

v-show:用来经常调整显示状态的标签上;

使用v-else

<!DOCTYPE html>
<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库 -->
  <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
      }
    },
    // 我们使用 v-if 与 v-show 两种方式来实现条件渲染
    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>

运行结果

image-20210612195830866.png

使用v-else-if

<!DOCTYPE html>
<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库 -->
  <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
      }
    },
    // 我们使用 v-if 与 v-show 两种方式来实现条件渲染
    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>

运行结果

image-20210612200220753.png

相关文章

网友评论

      本文标题:【Vue3 从入门到实战 进阶式掌握完整知识体系】006-Vue

      本文链接:https://www.haomeiwen.com/subject/nnuryltx.html