有时,使用vue在渲染元素时,会根据不同的条件判断加载不同的template模板内容,经常会尽可能地复用已有的元素而非全部重新写,比如:
<div id="app">
<template v-if="type === 'name'">
<label>用户名:</label>
<input placeholder="输入用户名">
</template>
<template v-else>
<label>邮箱:</label>
<input placeholder="输入邮箱">
</template>
<button @click="handleToggleClick">切换输入类型</button>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
type:'name'
},
methods:{
handleToggleClick:function(){
this.type = this.type === 'name'?'mail':'name';
}
}
})
</script>
输入内容后,DOM改变了,但是输入框里的内容依然保留着,说明输入框被复用了。
如果不希望是这个效果,可以使用vue的key属性,它可以自定义让我们决定是否要复用元素,key的值必须唯一。
修改后的代码如下:
<div id="app">
<template v-if="type === 'name'">
<label>用户名:</label>
<input placeholder="输入用户名" key="name-input">
</template>
<template v-else>
<label>邮箱:</label>
<input placeholder="输入邮箱" key="mail-input">
</template>
<button @click="handleToggleClick">切换输入类型</button>
</div>
<script>
var app = new Vue({
el:'#app',
data:{
type:'name'
},
methods:{
handleToggleClick:function(){
this.type = this.type === 'name'?'mail':'name';
}
}
})
</script>
加完key属性后,就不会复用了,切换类型时输入的内容也会被删除。