一、bug原因
由於網絡請求是異步操作,所以在渲染頁面的時候,數據還沒有過來,就可能會有下面的報錯
<span> <img :src="commentInfo.user.avatar" alt="" class="avatar"> </span>

數據結構:
二、定義數據模板
提前定義好數據模板:
//正確data() { return { commentInfo: { user:{}, }, },
//錯誤
data() {
return { commentInfo: {}, },
三、示例
//子組件
<template>
<span><img :src="commentInfo.user.avatar"
alt=""
class="avatar"></span>
<span>{{commentInfo.user.uname}}</span>
<template>
<script>
props: {
commentInfo: {
type: Object,
default() {
return {};
}
}
},
</script>
//父組件 <template> <div class="detail"> <detail-comment-info :commentInfo="commentInfo" /> </div> </template> <script> import detailCommentInfo from "./childComps/detailCommentInfo"; export default { name: "detail", data() { return { commentInfo: { user:{} //此處加入默認空對象 }, }, components: { detailCommentInfo, }, created() { this.iid = this.$route.params.iid; getDetail(this.iid).then(res => { const data = res.result; //如果評論數不等於0 if (data.rate.cRate !== 0) { this.commentInfo = data.rate.list[0]; console.log(this.commentInfo); } }); }, };
</script>