Vue3中的模板指令——列表渲染指令v-for

本文详细介绍了Vue3中的列表渲染指令v-for,包括遍历数组和对象,模板标签使用,直接应用在组件上,渲染策略,v-for与v-if的配合,以及Vue如何监听数组变化。同时,讨论了在v-for操作中应如何处理原数组的变更方法,以确保数据的响应式更新。
摘要由CSDN通过智能技术生成
4.6.2 列表渲染指令v-for

v-for指令相当于根据组件实例中的数组数据来批量渲染生成大量的新的li数据标签,其遍历形式如下:

4.6.2.1 遍历数组

items为组件实例属性,item为遍历数据对象,index为数据索引,

item in itemsitem of items(item,index) in items {} in items({},index) in items

const items = ref([{ message: 'Foo' }, { message: 'Bar' }])

// 数组遍历,item为数组中的对象
<li v-for="item in items">
  {
  { item.message }}
</li>

const parentMessage = ref('Parent')
const items = ref([{ message: 'Foo' }, { message: 'Bar' }])

// 数组中的对象解构赋值遍历
<li v-for="(item, index) in items">
  {
  { parentMessage }} - {
  { index }} - {
  { item.message }}
</li>

// 本示例说明:v-for中变量的作用域同JavaScript代码中的作用域
const parentMessage = 'Parent'
const items = [
  /* ... */
]

items.forEach((item, index) => {
  // 可以访问外层的 `parentMessage`
  // 而 `item` 和 `index` 只在这个作用域可用
  console.log(parentMessage, item.message, index)
})

// 数组中的对象部分解构赋值遍历
<li v-for="{ message } in items">
  {
  { message }}
</li>

<!-- 有 index 索引时 -->
<li v-for="({ message }, index) in items">
  {
  { message }} {
  { index }}
</li>i>

// v-for嵌套遍历
<li v-for&#
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南腔北调-pilmar

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值