<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./vue.global.js"></script>
</head>
<body>
<div id="app">
<div v-for="(item, index) in list" :key="item">
{{item}} {{index}}
</div>
<div v-for="(value,key, index) in info" :key="key">{{value}} {{key}} {{index}}</div>
<div v-for="(item, index) in num" :key="item">{{item}} {{index}}</div>
</div>
<script>
let vm = Vue.createApp({
data() {
return {
list: ["a", "b", "c"],
info: { usename: "zhuzhu", age: 22 },
num: 10,
};
},
}).mount("#app");
</script>
</body>
</html>
元素不加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>
<script src="./vue.global.js"></script>
</head>
<body>
<div id="app">
<!-- key当作index 和不加key错误是一样的 -->
<div v-for="(item, index) in list" :key="item">
{{item}} {{index}}
<input type="text" />
</div>
</div>
<script>
let vm = Vue.createApp({
data() {
return {
list: ["a", "b", "c"],
};
},
}).mount("#app");
setTimeout(() => {
vm.list.unshift("d");
}, 2000);
</script>
</body>
</html>
不加key或者key作为index的错误一致 2秒之前的效果
过2秒之后数组追加元素d 发现input不追随元素 这就是没有key
加key 才是正确的结果