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

问题复现

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

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
    }
  },
}

以上代码的作用为从父主键获得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项目效果是正常显示的呢?而刷新页面就报错了。
猜测:修改代码时,项目效果同步更新,但是未将对象重新声明。

你可能感兴趣的:(vue-cli3脚手架- Cannot read property 'name' of undefined")