820 字
3 分钟阅读
Vue – v-for
简介
Vue v-for
代码演示
<html>
<head>
<title>Vue v-for</title>
<style>
table, th, td {
border: 1px solid black;
width: 500px;
text-align: center;
}
table {
border-collapse: collapse;
}
</style>
</head>
<body>
<div id = "app">
<table>
<thead>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</thead>
<tbody>
<!-- 循环遍历 empList -->
<!-- v-for="(变量,下标) in 循环变量" -->
<!-- 变量:为遍历出来的元素 -->
<!-- 循环变量:为便利的列表 -->
<!-- 下标:字面意思 可以省略 -->
<!-- key 参数 -->
<!-- 作用:给元素添加的唯一标识,便于vue进行列表项的正确排序复用,提升渲染性能 -->
<!-- 推荐使用id作为key(唯一),不推荐使用index作为key(会变化,不对应) -->
<tr v-for="emp in empList" :key = "emp.id">
<td>{{emp.id}}</td>
<td>{{emp.name}}</td>
<td>{{emp.age}}</td>
</tr>
</tbody>
</table>
</div>
<script type="module">
import { createApp, ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
createApp({
data(){
return {
empList: [
{
id: 1,
name: '小王',
age: 18
},
{
id: 2,
name: '小李',
age: 19
},
{
id: 3,
name: '小张',
age: 20
}
]
}
}
}).mount('#app')
</script>
</body>
</html>
效果

