关于v-for的item-index-key的理解

本文详细介绍了Vue.js中的v-for指令,包括其在遍历数组、对象、字符串和指定次数时的用法。通过示例展示了如何在HTML中使用v-for显示人员列表、汽车信息,并演示了遍历字符串和指定次数的场景。实例代码清晰地展示了v-for的语法结构及其在实际应用中的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

v-for指令:
  1.用于展示列表数据
  2.语法:v-for="(item, index) in xxx" :key="yyy"
  3.可遍历:数组、对象、字符串(用的很少)、指定次数(用的很少)

遍历数组

   <h2>人员列表(遍历数组)</h2>
   <ul>
    <li v-for="(item,index) in person" :key='index'>
      {{item}}--{{index}} 
      <!-- 输出值为 -->
      <!-- { "id": "001", "name": "张三", "age": 18 }--0 -->
      <!-- { "id": "002", "name": "李四", "age": 19 }--1 -->
      <!-- { "id": "003", "name": "王五", "age": 20 }--2 -->
    </li>
   </ul>

遍历对象

   <h2>汽车信息(遍历对象)</h2>
   <ul>
    <li v-for="(item,key,index) in car" :key="index">
        {{item}}--------{{key,}}-----{{index}}
        <!-- 输出值为 -->
        <!-- 比亚迪--------name-----0 -->
        <!-- 20--------price-----1 -->
        <!-- 黑色--------color-----2 -->
    </li>
   </ul>

遍历字符串

   <h2>测试遍历字符串(用得少)</h2>
   <ul>
    <li v-for="(item,index) in str" :key="index">
      {{item}}----{{index}}
      <!-- 输出值为 -->
        <!-- h----0 -->
        <!-- e----1 -->
        <!-- l----2 -->
        <!-- l----3 -->
        <!-- o----4 -->
    </li>
   </ul>

遍历指定次数

<h2>测试遍历指定次数(用得少)</h2>
   <ul>
    <li v-for="index in 5" :key="index">
      {{index}}
      <!-- 输出值为 -->
        <!-- 1 -->
        <!-- 2 -->
        <!-- 3 -->
        <!-- 4 -->
        <!-- 5 -->
    </li>
   </ul>
  </div>
  </div>
<script>
  export default {
    data() {
      return {
        person:[
        {id:'001',name:'张三',age:18},
        {id:'002',name:'李四',age:19},
        {id:'003',name:'王五',age:20}
        ],
        car:{
          name:"比亚迪",
          price:"20万",
          color:"黑色"
        },
        str:"hello"
      }  
    },
  }
</script>

<style lang="less" scoped>

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值