Vue条件渲染 v-if,v-else-if,v-else,v-show

1 v-if指令

1.1 v-if:根据表达式的布尔值判断是否插入标签 

v-if指令,当show为true时显示div内容,当show为false时隐藏div内容   
<div id="root">
        <div v-if="show">hello wirld</div>
        <button @click="handle">toggle</button>
        </div>
    <script>
        new Vue({
            el: "#root",
            data:{
                show:true,
            },
            methods:{
              handle: function () {
                  this.show=!this.show;
              }
            }
        })
    </script>

展示

1.2  v-else v-else-if

   v-else紧跟在v-if或v-else-if之后

   v-else-if紧跟在v-if或v-else-if之后

如下例:

<div id="root">
    <div v-if="show===a">This is A</div>
    <div v-else-if="show===b">This is B</div>
    <div v-else>This is others</div>
</div>
<script>
    var vm=new Vue({
        el:root,
        data:{
            show: true
        }
    })
</script>

 结果:

1.3 使用key值管理可复用的元素

以下两个实例展示了不使用key值与使用key值的区别

实例:不使用key值
<div id="root">    
    <div v-if="show">
        用户名: <input type="text">
    </div>
    <div v-else>
        邮箱名: <input type="text">
    </div>
    <div>
    <button @click="handleClick"> 切换</button>
    </div>
</div>
<script>
    var vm=new Vue({
        el:root,
        data:{
            show: true
        },
        methods:{
            handleClick: function () {
               this.show=!this.show
            }
        }
    })
</script>

 结果展示:

 

实例:使用key值 
<div id="root">   
    <div v-if="show">
        用户名: <input type="text" key="username">
    </div>
    <div v-else>
        邮箱名: <input type="text" key="email">
    </div>
    <div>
    <button @click="handleClick"> 切换</button>
    </div>
</div>
<script>
    var vm=new Vue({
        el:root,
        data:{
            show: true
        },
        methods:{
            handleClick: function () {
               this.show=!this.show
            }
        }
    })
</script>

结果展示: 

 

2、v-show  

 根据表达式的布尔值判断是否显示标签 

v-show指令
<div id="root">
        <div v-show="show">hello wirld</div>
        <button @click="handle">toggle</button>       
    </div>
    <script>
        new Vue({
            el: "#root",
            data:{
                show:true,
             },
            methods:{
              handle: function () {
                  this.show=!this.show;
              }
            }
        })
    </script>

3、v-if和v-show的区别:

v- else-if

v-else

  1. v-if通过删除和添加标签实现标签的隐藏和显示
  2. v-show通过设置标签的display属性来实现标签的隐藏和显示

猜你喜欢

转载自blog.csdn.net/willard_cui/article/details/82227240