【问题标题】:Vuejs undefined object inside a watched property [duplicate]监视属性中的Vuejs未定义对象[重复]
【发布时间】:2018-08-01 01:47:33
【问题描述】:

我在 Vuejs 中遇到了监视属性的问题。我得到的错误 - Cannot read property 'list' of undefined 即使列表 is 已定义。 我在执行 if 检查后收到错误消息(在 var index .... 行)。

watch: {
   selectedRole: () => {
     if (this.modifiedUser.list) {
        var index = this.modifiedUser.list.findIndex(obj => obj.id == 
               this.selectedObj);
        this.modifiedUser.list[index].object = Object.assign({}, this.selectedObj);
  }
}

知道为什么它通过了 if 语句中的检查但在下一行失败了吗?

VueJs - v2.5.2.

【问题讨论】:

  • 这个错误并不意味着list是未定义的,而是modifiedUser是。
  • 你可以试试if (this.modifiedUser && this.modifiedUser.list)作为你的条件吗?
  • @MicaelNussbaumer 我做了,现在它仍然进入 if 语句,但 var index 变量未定义。
  • 从 if 语句中取出var index,并在其上方为其赋予默认值。然后在 if 语句中更新它,如果 if 语句为真

标签: vue.js vuejs2


【解决方案1】:

请在if (this.modifiedUser.list) { 中尝试检查 modifiedUser 是否未定义。

还要检查索引是否未定义:

var index = this.modifiedUser.list.findIndex(obj => obj.id == this.selectedObj);

希望对你有帮助

【讨论】:

  • 定义了修改的用户,但是检查失败。
猜你喜欢
  • 1970-01-01
  • 2018-04-08
  • 2010-11-19
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
相关资源
最近更新 更多