Vue 会尽可能高效地渲染元素,通常会复用已有元素而不是从头开始渲染。
<template v-if="type">
<label>Usernamelabel>
<input type="text" placeholder="enter your username">
template>
<template v-else>
<label>Emaillabel>
<input type="text" placeholder="enter your email">
template>
<button @click="toggleType">切换button>那么在上面的代码中切换 loginType 将不会清除用户已经输入的内容。因为两个模板使用了相同的元素, 不会被替换掉——仅仅是替换了它的 placeholder。
可以通过添加一个具有唯一值的 key 属性,来达到每次切换时,输入框都将被重新渲染
<template v-if="type">
<label>Usernamelabel>
<input type="text" placeholder="enter your username" key="username">
template>
<template v-else>
<label>Emaillabel>
<input type="text" placeholder="enter your email" key="email">
template>
<button @click="toggleType">切换button>注意, 元素仍然会被高效地复用,因为它们没有添加 key 属性。
<template v-show="false">
<p>哈哈哈p>
template>上述内容仍然会被显示出来!注意, v-show 不支持