<!doctype html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="../css/normalize.css">
<script src="../js/vue2.6.11.js"></script>
<style type="text/css">
input[type="text"]{
height: 37px;
width: 100px;
}
input[type="button"]{
height: 43px;
width: 80px;
vertical-align: bottom;
}
table,tr,th,td{
border: #ddd solid 1px;
border-collapse:collapse
}
</style>
</head>
<body>
<div id="app">
<div>
學名:<input type="text" v-model="name">
生存狀態:<input type="text" v-model="survive">
<input type="button" value="add" @click="add">
</div>
<table>
<tr>
<th></th>
<th>序號</th>
<th>學名</th>
<th>生存狀態</th>
</tr>
<!-- 選中一行,如果沒有:key,添加數據後,所選中的行將會錯亂 -->
<tr v-for="(plant,i) in plants" :key="plant.id">
<td><input type="checkbox"></td><td>{{plant.id}}</td><td>{{plant.name}}</td><td>{{plant.survive}}</td>
</tr>
</table>
</div>
<script>
var vm = new Vue({
el: '#app',
data:{
id:3,
name:"",
survive:"",
plants:[
{id:1,name:"中華古果",survive:"已滅絕"}
,{id:2,name:"光葉蕨",survive:"已滅絕"}
,{id:3,name:"篦齒蘇鐵",survive:"已滅絕"}
]
},
methods:{
add(){
this.plants.unshift({id:++this.id,name:this.name,survive:this.survive});
}
}
});
</script>
</body>
</html>
vueJS 009 v-for 中的key注意事項
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.