【问题标题】:[Vue warn]: Error in render: "TypeError: Cannot read property 'type' of undefined"[Vue 警告]:渲染错误:“TypeError:无法读取未定义的属性‘类型’”
【发布时间】:2020-04-07 23:34:53
【问题描述】:

我的数组有一个数据。 为什么我的控制台会弹出这个错误:

渲染错误:“TypeError:无法读取未定义的属性‘类型’”

方法内的vue代码:

getRoomType(assign_id){
 return this.roomTypeName.find(o => o.room_id === parseInt(assign_id)).type;
},

vue html:

<span>{{ option.value }} ({{(option.assign_id=='no')? 'unassign' : getRoomType(option.assign_id) }})</span>

错误:

【问题讨论】:

  • 添加错误消息文本。嵌入图片。
  • 欢迎来到 SO。以后,请将错误消息的文本添加到您的帖子正文中。如果用户想在尝试对代码进行故障排除时对消息运行 Google 搜索,则可以更轻松地复制/粘贴。添加图片也可以,作为补充,如果您认为它会有所帮助。但通常没有必要。无论是苦笑,始终将错误消息和代码作为文本输入到您的帖子正文中。此外,使用引号中的错误消息搜索 SO 或 Google 通常会引导您找到解决方案。例如:` js "TypeError: cannot read property of undefined"`

标签: javascript vue.js undefined


【解决方案1】:

我终于解决了我的问题。

解决方法:(返回值前检查数组的长度,确保有数据要返回。)

getRoomType(assign_id){
    return (this.roomTypeName.length > 0)? this.roomTypeName.find(element => element.room_id === parseInt(assign_id)).type :'error';
},

【讨论】:

  • find 找不到怎么办? :p
  • 不返回任何内容或返回错误并提示我所做的事情,所以它会给你一个想法。
  • 如果.find 什么也没找到,你的代码会抛出错误,因为undefined 没有type 的属性——换句话说,这根本没有解决问题
猜你喜欢
  • 2021-02-17
  • 2018-07-14
  • 2021-03-21
  • 2021-08-18
  • 2020-09-17
  • 2020-01-01
  • 1970-01-01
  • 2018-10-01
  • 2019-12-01
相关资源
最近更新 更多