【Vue-bug】vue.esm.js?a026:628 [Vue warn]: Error in render: "TypeError: Cannot read property 'avatar' of undefined"


一、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>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM