【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