• vue-cli3脚手架- Cannot read property 'name' of undefined"


    问题复现

    使用vue-cli 框架对组件进行赋值时报错:Cannot read property 'name' of undefined"
    代码:

    <template>
      <el-row :gutter="0">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <img class="head-img" src="../assets/img/default.png" alt="头像" />
          <h3 class="user-name">{{ name }}</h3>
          <p class="user-msg">{{ msg }}</p>
        </el-col>
      </el-row>
    </template>
    
    export default {
      name: "mes",
      props: {
        nubmer: Number,
        user_msg: Array,
      },
      computed: {
        name:function(){
          return this.user_msg[his.nubmer].name
        },
        msg:function(){
          return this.user_msg[this.nubmer].msg
        }
      },
    }
    </script>
    

    以上代码的作用为从父主键获得number、user_msg,在computed中处理将user_msg数组中的某个对象中的某值赋值给 {{ name }}、和{{ msg }}
    vue-cli编译好,启动app后一步一步保存查看实时效果时未报错,但是刷新页面时报错
    Cannot read property 'name' of undefined"

    解决方法


    上网寻找解决方法,在该帖中获得答案:该贴入口
    异步请求获取数据时,由于数据时异步获取的,所以一开始是没有该数据属性的,这种情况下也会报这种错误。
    比如说我这里有一个数据info,初始值为一个空对象。{{info.supports}}是不会报错的,但是,{{info.supports.name}}这样就会报错了。这是为什么呢?
    因为,info.supports已经是一个undefined了,你undefined.name就肯定会报错了

    代码修改


    修改 computed中代码

    computed: {
        name:function(){
          return ((this.user_msg||{})[this.nubmer]||{}).name
        },
        msg:function(){
          return ((this.user_msg||{})[this.nubmer]||{}).msg
        }
      }
    

    编译通过,这样写在访问对象中值的时候如果对象未undefined时,创建一个空对象。

    思考:为什么在改代码的时候,app项目效果是正常显示的呢?而刷新页面就报错了。
    猜测:修改代码时,项目效果同步更新,但是未将对象重新声明。

  • 相关阅读:
    软件设计中的立足点
    Clojure基础
    团队凝聚力
    执行力与领导力
    工作与生活
    分离焦虑OR责任焦虑
    保持激情
    立足点
    论研发管理--开篇
    初级码农常犯错误
  • 原文地址:https://www.cnblogs.com/hjc-12580/p/12090160.html
Copyright © 2020-2023  润新知