vue在template块里使用v-for循环对象、数组及嵌套结构数据
目录
一、基本数据类型
二、循环对象
三、循环数组及嵌套结构
四、其他类型循环
五、总结
一、基本数据类型
在vue中,有对象、数组、字符串、数字等类型的结构,在模板渲染时,可以使用v-for省略大部分重复性的代码,特别是对对象和数组及对象和数组相互嵌套的结构的循环。我们需要了解遍历相关对象的key或value的写法。
二、循环对象
对象就是由几组key:value形式所组成的一个结构对象,对应python中的字典。在vue中循环对象的话,可以选择只循环key或只循环value,当然也可以一组一组循环。
<template>
<!-- 只循环值的话使用解包形式,用index作为key。因为value可能会有重复,尽量不重复。 -->
<template v-for="(value, index) in Object.values(obj)" :key="index">
<p style="text-align: center;">{{ value }}</p>
</template>
<template v-for="key in Object.keys(obj)" :key="key">
<p style="text-align: center;">{{ key }}</p>
</template>
<template v-for="(value, key, index) in obj" :key="key">
<p style="text-align: center;">{{ index }}.{{ key }}-{{ value }}</p>
</template>
</template>
<script setup>
import { ref, reactive } from 'vue'
const obj = reactive({
'title': 'title1',
'content': 'content1'
})
</script>
三、循环数组及嵌套结构
数组由多个项组成的,同python中的列表概念一样。循环列表,一样可以使用上述方法。
<template>
<!-- 不带index的循环列表中每一项 -->
<template v-for="item in listObj" :key="item.title">
<p style="text-align: center;">{{ item.title }}-{{ item.content }}</p>
</template>
<!-- 带index循环列表 -->
<template v-for="(item, index) in listObj" :key="index">
<p style="text-align: center;">{{ index }}.{{ item.title }}-{{ item.content }}</p>
</template>
<!-- 嵌套结构,逐级解包循环 -->
<template v-for="(item, index) in listObj" :key="index">
<template v-for="(value, key, _) in item" :key="key">
<p style="text-align: center;">{{ index }}.{{ item.title }}-{{ item.content }}</p>
</template>
</template>
</template>
<script setup>
import { ref, reactive } from 'vue'
const listObj = reactive([
{
'title': 'title2',
'content': 'content2'
},
{
'title': 'title3',
'content': 'content3'
}
])
</script>
四、其他类型循环
其余类型的循环就比较好理解了,字符串则是循环每一个字符,数字循环则是从小到大。
<template>
<!-- 循环数字(可以带index) -->
<template v-for="i in 3" :key="i">
<p style="text-align: center;">{{ i }}</p>
</template>
<!-- 循环字符串(可以带index) -->
<template v-for="i in 'String'" :key="i">
<p style="text-align: center;">{{ i }}</p>
</template>
</template>
五、总结
通过上面几种数据类型的遍历,发现循环的值可以有两个及以上的值,最后一个为当前遍历值在遍历对象下的index。且当遍历对象时,vue遵循值优先的理念,占位顺序分别为value, key,这点和其他语音有出入。
对象:v-for="(value, key, index) in obj"
数组:v-for="(item, index) in arr"