v-for循环空数组时,id报错undefined(已解决)

问题:在轮播图子组件中v-for循环渲染图片,但是报错Error in render: "TypeError: Cannot read properties of undefined (reading 'id')"

html结构如下:
```html
 <div class="swiper" ref="swipernow">
        <div class="swiper-wrapper">
          <div class="swiper-slide" v-for="{item,index} in skuImageList" :key="item.id">
            <img :src="item.imgUrl" alt="" :class="{current:currentIndex===index}" @click=changeIndex(index) />
          </div>
        </div>

js代码如下:

 props: ['skuImageList'],
  computed: {
    // 保证至少skuImageList[0]是个空的对象
    ImageList() {
      return this.skuImageList[0] || {}
    }
  },

其中,props中skuImageList的值来自于父组件,代码如下

computed: {
    ...mapGetters(['getCategoryView', 'getSkuInfo', 'getSpuSaleAttrList']),
    skuImageList() {
      // 保证如果服务器太慢,传进来的至少是一个空数组
      return this.getSkuInfo.skuImageList || []
    }
  }

报错:

img


个人分析原因:可能是在父组件中规定了this.getSkuInfo.skuImageList || [],所以当skuImageList返回值是空数组时,子组件对skuImageList进行for循环遍历,skuImageList中的item依然是空,item.id就是undefined。
尝试过在for循环的父元素swiper-wrapper中加入判断条件v-if="skuImageList!=[]",想让它判断当传过来的skuImageList不等于空数组的时候再执行下面的循环渲染操作,但是仍旧报错,有没有人帮忙看看这个该怎么解决~感谢

解决:在for循环的父元素swiper-wrapper中加入判断条件v-if的思路正确,但是具体语句出了问题,应该写为v-if="skuImageList.length!=0“,后面没有再报错了。


<template v-for="{item,index} in skuImageList" >
            <div class="swiper-slide"  :key="item.id">
            </div>
 </template>

id未定义 你数据里有吗

你item里面有id吗