bug
写轮播图的时候报错:
TypeError: Cannot read properties of undefined (reading ‘topModule’)
显示mainPart不存在,但是显示出了图片。
对应代码:
html:
<detailSwipe :swipe-data="detailData.mainPart.topModule.housePicture.housePics"/>
<!-- 轮播图 -->
<template>
<div class="swipe">
<van-swipe class="my-swipe" :autoplay="3000" lazy-render>
<van-swipe-item v-for="item in props.swipeData" :key="item">
<img :src="item.albumUrl" />
</van-swipe-item>
</van-swipe>
</div>
</template>
<script setup>
const props = defineProps({
swipeData: {
type: Array,
default: () => []
}
})
</script>
js:
const detailStore = useDetailStore()
detailStore.fetchDetailData(houseId)
const { detailData } = storeToRefs(detailStore)
fetchDetailData
:
import { defineStore } from "pinia";
import { getDetailInfos } from '@/service/modules/detail'
const useDetailStore = defineStore('detail', {
state: () => {
return {
detailData: {},
}
},
actions: {
async fetchDetailData(houseId) {
const res = await getDetailInfos(houseId)
// console.log(res)
this.detailData=res.data
}
}
})
export default useDetailStore
debug
控制台报错显示mainPart不存在,但页面却显示出了mainPart存在。说明:一开始mainPart不存在,之后又存在了。
分析代码发现,detailData
是响应式的,而detailData
的数据是通过网络请求fetchDetailData
得到,网络请求需要时间。
一开始页面渲染的时候还没有请求到数据,此时mainPart不存在,控制台会报错,网络请求到数据之后就存在了,页面显示出数据,但报错不会取消。
这个报错虽然不用管也不会影响页面的显示(?),但我们还是要解决它。
解决方法1:可选链运算符?.
<detailSwipe :swipe-data="detailData?.mainPart?.topModule?.housePicture?.housePics"/>
有用但麻烦,太多?
了。
解决方法2:v-if
<div class="main" v-if="detailData.mainPart">
<detailSwipe :swipe-data="detailData.mainPart.topModule.housePicture.housePics" />
</div>
不报错了。