因為 v-if 是一個指令,所以必須將它添加到一個元素上。
在 <template> 元素上使用 v-if 條件渲染分組, <template> 元素當做不可見的包裹元素,並在上面使用 v-if。最終的渲染結果將不包含 <template> 元素。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>v-if 指令</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div id="app"> <button v-on:click="open">開始</button>{{number}} <div v-if="number > 90">特等獎</div> <div v-else-if="number > 80">一等獎</div> <div v-else-if="number > 70">二等獎</div> <div v-else-if="number > 60">三等獎</div> <div v-else-if="number > 50">再來一次</div> <div v-else>謝謝參與</div> </div> </body> </html> <script> var app = new Vue({ el: "#app", data: { number: 0 }, methods: { open: function() { this.number = Math.random() * 100 } } }) </script>
用 key 管理可復用的元素,因為兩個模板使用了相同的元素,<input> 不會被替換掉——僅僅是替換了它的 placeholder。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>v-if 指令</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div id="app"> <template> <div v-if="loginType === 'username'"> <label>username</label> <input type="text" placeholder="enter your username"> </div> <div v-else> <label>passworld</label> <input type="password" placeholder="enter your password"> </div> </template> <template> <div v-if="loginType === 'username'"> <label>username</label> <input type="text" placeholder="enter your username" key="a"> <!--vue是高效復用的,input還是2個input,當時輸入緩存還在,為了區別開,用關鍵字key--> </div> <div v-else> <label>passworld</label> <input type="password" placeholder="enter your password" key="b"> <!--key 在瀏覽器控制台不顯示哦,但能完美解決問題--> </div> </template> <button v-on:click="fun">點擊切換</button> </div> </body> </html> <script> var app = new Vue({ el: "#app", data: { loginType: 'username', }, methods: { fun: function() { this.loginType == 'username' ? this.loginType = 'password' : this.loginType = 'username'; } } }) </script>
所以 Vue 為你提供了一種方式來表達“這兩個元素是完全獨立的,不要復用它們”。只需添加一個具有唯一值的 key attribute 即可,每次切換時,輸入框都將被重新渲染,達到清除緩存的目的。