【Vue-bug】vue.esm.js?a026:628 [Vue warn]: Error in render: "TypeError: Cannot read property 'avatar' of undefined"
阿新 • • 發佈:2020-08-01
由於網路請求是非同步請求,所以在渲染頁面的時候,資料還沒有過來,就可能會有下面的報錯
<span>
<img :src="commentInfo.user.avatar"
alt=""
class="avatar">
</span>
資料結構:
所以需要提前定義好資料模板:
data() {
return {
commentInfo: {
user:{}
},
},
示例:
//子元件 <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); } }); }, };
//父元件 <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); } }); }, };