Vue v-for遍历详细使用

前言

  • 当v-for遍历的时候,一个参数是每一项值(item),2个参数是每一项值和索引(item,index),3个参数*是每一项值,索引,下标(item,index,i)。

  • 当v-for遍历对象时,每一项,索引,下标,都有值。下标从0开始。

  • 当v-for遍历数组对象时,每一项,索引,有值。 下标没有值,索引从0开始。

  • 当v-for遍历数字时,每一项,索引,有值。下标没有值,索引从0开始,会跟上面的索引相同报错,不影响使用。

全部代码

<template>
  <div class="box">
    <div class="son" v-for="(item, index, i) in data" :key="index">
      <p>值:{
   
   { item }}</p>
      <p>索引:--- {
   
   { index }}</p>
      <p>下标:--- {
   
   { i }}</p>
      <p>v-for遍历对象</p>
    </div>
    <div class="son" v-for="(item, index, i) in datae" :key="index">
      <p>值:{
   
   { item }}</p>
      <p>索引: --- {
   
   { index }}</p>
      <p>下标: --- {
   
   { i }}</p>
      <p>v-for遍历对象(有索引和下标形式)</p>
    </div>
    <div class="son" v-for="(item, index, i) in dataer" :key="index">
      <p>值:{
   
   { item }}</p>
      <p>索引: --- {
   
   { index }}</p>
      <p>下标: --- {
   
   { i }}</p>
      <p>v-for遍历数组对象</p>
    </div>
    <!-- 注释掉下面这一段报错就会没了 -->
    <div class="son" v-for="(item, index, i) in 3" :key="index">
      <p>值:{
   
   { item }}</p>
      <p>索引:--- {
   
   { index }}</p>
      <p>下标:--- {
   
   { i }}</p>
      <p>v-for遍历数字</p>
    </div>
    <div class="title">
      结论:
      <p>
        当v-for遍历的时候,<span>一个参数</span>是每一项值(item),<span>2个参数</span>是每一项值和索引(item,index),<span>3个参数</span>是每一项值,索引,下标(item,index,i)。
      </p>
      <p>当v-for遍历对象时,每一项,索引,下标,都有值。下标从0开始。</p>
      <p>
        当v-for遍历数组对象时,每一项,索引,有值。 下标没有值,索引从0开始。
      </p>
      <p>
        当v-for遍历数字时,每一项,索引,有值。
        下标没有值,索引从0开始,会跟上面的索引相同报错,不影响使用。
      </p>
    </div>
  </div>
</template> 
​
<script>
export default {
  data() {
    return {
      data: {
        id: 12,
        name: "安康几十年",
        conta: "jshbkj",
      },
      datae: {
        10: { id: 6, name: "战三" },
        你好: { id: 7, name: "ajsd" },
        张三: { id: 8, name: "jskj" },
      },
      dataer: [
        { id: 3, name: "战三" },
        { id: 4, name: "ajsd" },
        { id: 5, name: "jskj" },
      ],
    };
  },
};
</script>
​
<style lang="scss" scoped>
.box {
  width: 100%;
  height: 800px;
  background-color: #fff;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  .son {
    width: 33.33%;
    height: 120px;
    padding-top: 20px;
    // background-color: skyblue;
    border-bottom: 1px solid #ccc;
    text-align: center;
    p:last-child {
      color: skyblue;
      font-size: 18px;
    }
  }
  .title {
    font-size: 25px;
    font-weight: 700;
    p {
      font-size: 18px;
      margin: 10px 0;
      span {
        color: red;
      }
    }
  }
}
</style>

运行结果

一般后端返回来的数组对象数据,都会有索引

这个报错是遍历数字,他的索引和上面012相同导致的,把他注释掉就可以了,不影响使用。


经过这一趟流程下来相信你也对 Vue v-for遍历详细使用 显示文件图标 搜索 更改样式 有了初步的深刻印象,但在实际开发中我 们遇到的情况肯定是不一样的,所以我们要理解它的原理,万变不离其宗。加油,打工人!

什么不足的地方请大家指出谢谢 -- 風过无痕

猜你喜欢

转载自blog.csdn.net/weixin_53579656/article/details/129461433