·用于根据条件控制元素的创建与移除。

    v-if 指令 - 图1

    <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Document</title> </head> <body> <div id=“app”> <p v-if=“bool”>这是标签内容</p> <p v-else-if=“false”>这是第二个p标签</p> <p v-else-if=“false”>这是第三个p标签</p> //上面的生效,这个不会生效 <p v-else>最后一个p标签</p> </div> <script src=“lib/vue.js”></script> <script> var vm = new Vue({ el: ‘#app’, data: { bool: false } }); </script> </body> </html>

    给使用v-if的同类型元素绑定不同的key

    <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Document</title> </head> <body> <div id=“app”> <div v-if=“type===’username’” :key=“‘username’”> 用户名输入框:<input type=“text”> </div> <div v-else :key=“‘email’”> 邮箱输入框:<input type=“text”> </div> </div> <script src=“lib/vue.js”></script> <script> var vm = new Vue({ el: ‘#app’, data: { bool: true, type: ‘username’ } }); </script> </body> </html>

    出于性能考虑,应避免将v-if与v-for应用于同一标签,可将v-if设置给父标签

    v-for优先级更高

    <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <title>Document</title> </head> <body> <div id=“app”> <ul v-if=“false”> <li v-for=“item in items”>{{item}}</li> </ul> </div> <script src=“lib/vue.js”></script> <script> var vm = new Vue({ el: ‘#app’, data: { items: { content1: ‘内容1’, content2: ‘内容2’, content3: ‘内容3’ } } }); </script> </body> </html>