v-for in vue can loop four kinds of data, namely, numbers, strings, arrays, objects
First of all, v-for is an attribute, which is an extension to the attribute of an element. Remember, it is v-for = "", not v-for: "".
Then, the value of the v-for attribute is an expression, and the parameters inside are separated by commas instead of spaces.
One: v-for cycle number
<li v-for='num in 10'>{{ num }}</li>
Two: v-for loop string
<li v-for="str in 'haha'">{{ str }}</li>
Three: v-for loop array
<div id="test">
<ul>
<li v-for='(item,index) in arr'>{{ item }}---{{ index }}</li>
</ul>
</div>
<script>
const vm = new Vue({
el: "#test",
data: {
arr: ['apple', 'orange', 'banana'],
}
})
</script>
The above item, index is a semantic way of writing, not fixed, it can be a, b, c, the order is the array content, array index
Four: v-for loop object
<div id="test">
<ul>
<li v-for='(value,key,index) in obj'>{{ value }}---{{ key }}---{{ index }}</li>
</ul>
</div>
<script>
const vm = new Vue({
el: "#test",
data: {
obj: {
name: "zhangsan",
age: 18,
sex: '男'
}
}
})
</script>
The first is the value, the second is the key, and the third is the index
Explanation of the order of parameters in arrays and objects
1. All cycles, the primary purpose is to get the value
of the element 2. Second is the key
of the element 3. Finally is the index of the element
You can rely on this rule to remember the order of the parameters