问题:在轮播图子组件中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 || []
}
}
报错:
解决:在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吗