【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>
    注:以上内容仅用于日常学习

                
            
        
浙公网安备 33010602011771号