公司项目的安卓和iOS端又一个版本做完了,应该也是最后一次更新了,终于有时间继续学uni-app了。
我们可以使用 v-for 指令基于一个数组渲染一个列表。
v-for 指令的值需要使用 item in items 形式的特殊语法,其中 items 是源数据的数,item 是迭代项的别名:
<template>
<li v-for="item in items">
{{item.message}}
</li>
</template>
<script>
export default {
data() {
return {
items:[{message:'Foo'},{message:'Bar'}]
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
</style>
在 v-for 块中可以完整地访问父作用域内的属性和变量。v-for 也支持使用可选的第二个参数表示当前项的位置索引。
<template>
<li v-for="(item,index) in items">
{{parentMessage}} - {{index}} - {{item.message}}
</li>
</template>
<script>
export default {
data() {
return {
parentMessage:'Parent',
items:[{message:'Foo'},{message:'Bar'}]
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
</style>
v-for 变量的作用域和下面的 JavaScript 代码很类似:
const parentMessage = 'Parent'
const items = [
/* ... */
]
items.forEach((item, index) => {
// 可以访问外层的 `parentMessage`
// 而 `item` 和 `index` 只在这个作用域可用
console.log(parentMessage, item.message, index)
})
也可以在定义 v-for 的变量别名时使用解构,和解构函数类似:
<template>
<li v-for="{message} in items">
{{message}}
</li>
<br>
<!-- 有 index 索引时 -->
<li v-for="({message},index) in items">
{{message}}-{{index}}
</li>
</template>
<script>
export default {
data() {
return {
items:[{message:'Foo'},{message:'Bar'}]
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
</style>
对于多层嵌套的 v-for,作用域的工作方式和函数的作用域很类似。每个 v-for 作用域都可以访问到父级作用域:
<li v-for="item in items">
<span v-for="childItem in item.children">
{{ item.message }} {{ childItem }}
</span>
</li>
v-for 与对象
也可以使用 v-for 来遍历一个对象的所有属性。遍历的顺序会基于对该对象调用 Object.values() 的返回值来决定。
<template>
<ul>
<li v-for="value in myObject">
{{value}}
</li>
</ul>
<br>
<text>通过第二个参数表示属性名</text>
<ul>
<li v-for="(value,key) in myObject">
{{key}}: {{value}}
</li>
</ul>
<br>
<text>通过第三个参数表示位置索引</text>
<ul>
<li v-for="(value,key,index) in myObject">
{{index}}. {{key}}: {{value}}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
myObject:{
title:'v-for的使用',
author:'淑女',
publishedTime:'2025新年'
}
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
</style>
在 v-for 里使用范围值
<template>
<span v-for="n in 10"> {{n}} {{space}}</span>
</template>
<script>
export default {
data() {
return {
space:' '
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
</style>
注意这里 n 的初始值是 1,而不是 0。