v-for, as the name suggests, is used to traverse arrays or objects.
When using v-for to traverse objects to generate a list and the list data is in an updated state, you need to bind a key value to give vue a prompt, which is convenient for tracking the identity of each node instead of reusing and reordering existing elements. And, the key value is unique.
Sample code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue hello world</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<span v-for="e in user">
{
{ e }}
</span>
<hr>
<!-- 遍历数组-->
<ul>
<li v-for="i,index in nums">
{
{ index }} : {
{ i }}
</li>
</ul>
<hr>
<!-- 遍历对象-->
<span v-for="value,key,index in user">
{
{ index }} : {
{ key }} -- {
{ value }}
<br>
</span>
<hr>
<!-- 遍历对象数组-->
<span v-for="user,index in users" :key="user.id">
{
{ index }} : {
{user.name}} -- {
{ user.age }}
<br>
</span>
</div>
<script>
const app = new Vue({
//element 用来给vue实例定义一个作用范围
el: "#app",
// 用来给vue实例定义一些相关的数据
data: {
nums: [1, 24, 56, 23, 5],
users:
[{
id:0,name: "wuwl", age: 27}, {
id:1,name: "guopp", age: 25}],
user: {
name: "wuwl", age: 27}
}
,
methods: {
}
});
</script>
</body>
</html>
running result: