举个例子吧,一个非常简单的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
<!--
条件渲染指令
-->
<div id="app">
<template v-if="type === 'name'">
<label>用户名:</label>
<input type="text" placeholder="请输入用户名">
</template>
<template v-else>
<label>密码:</label>
<input type="password" placeholder="请输入密码">
</template>
<button @click="click">click me</button>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
type: 'name'
},
methods: {
click: function(){
this.type = this.type === 'name' ? 'password' : 'name';
}
},
})
</script>
</body>
</html>
这个例子输入内容之后,点击切换按钮,虽然说DOM变了,但是之前输入框中的输入内容却没有变化,看起来就只是换了label和placeholder,这就说明< input>标签被复用
了
但是说真的,很多时候我们不想要这种效果,我们可以使用vue提供的key属性
代码还是上面的代码,但是现在我们在input标签里加上不同的key值:
<template v-if="type === 'name'">
<label>用户名:</label>
<input type="text" placeholder="请输入用户名" key="name-input">
</template>
<template v-else>
<label>密码:</label>
<input type="password" placeholder="请输入密码" key="pwd-input">
</template>
再次测试运行发现没问题啦,这里需要提醒一句,那就是key的值必须是唯一的