Vue 条件渲染

  1. v-if:
    • 适用于频率较低的场景
    • 不展示的dom元素直接被移除
    • v-if,v-else-if,v-else可以一起使用,但要求结构不能被打断
  2. v-show
    • 适用于频率较高的场景
    • 不展示的dom元素未被移除,仅仅是使用样式隐藏掉
  3. 使用v-if时,元素可能无法获取到,而使用v-show一定可以获取到

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>Document</title>
</head>
<body>
    <div id="root">
        <h2 > 
             {{n}}
        </h2>
        <button @click="changemethod">clcik me</button>
        <div v-if="n===1">A</div>
        <div  v-else-if="n===2" >B</div>
        <div  v-else>C</div>
    <!-- template只能与v-if使用,不影响 -->
<template v-if="n===1">
    <h2>beijing</h2>
    <h2>shanghai</h2>
</template>
           
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    new Vue({
        el:"#root",
        data:{
            n:1
        },
        methods: {
            changemethod(){ (this.n)++}
          
        },
    })
</script>
</html>

v-show

<!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>Document</title>
</head>
<body>
    <div id="root">
        <h2 v-show='a'> 
            欢迎来到{{name}}
        </h2>
        <button @click="changemethod">clcik me</button>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    new Vue({
        el:"#root",
        data:{
            name:'尚硅谷',
            a:false,
        },
        methods: {
            changemethod(){this.a=!this.a ; }
          
        },
    })
</script>
</html>
posted @ 2021-11-16 20:00  ABkjlhkj  阅读(21)  评论(0)    收藏  举报