Vue 2:无法通过 "Cannot Read Property"

Vue 2: Can't Get Past "Cannot Read Property"

我刚刚将我的应用程序升级到 Vue 2,我似乎无法克服这个错误:

"Uncaught TypeError: Cannot read property 'length' of null at VueComponent.showChoices (eval at (app.js:310), :33:32)”

。我以为我是在有条件地保护自己免受这种情况的影响,但这个错误现在已经困扰了我 3 个小时。这是 showChoices:

showChoices() {
    if(this.filtered) {
        if (this.search.length > 2 && this.filtered.length > 0) {
            return true;
        }
    }
    return false;
}

null 值没有 length 属性。 正如您评论的那样,this.search 为空。你不是故意的吗?:

showChoices() {
  if (this.search && this.filtered) {
    if (this.search.length > 2 && this.filtered.length > 0) {
        return true;
    }
  }
  return false;
}

您还需要添加空检查,如下所示:

showChoices() {
    if (this.search && this.search.length > 2 && this.filtered && this.filtered.length > 0) {
      return true;
    }
    return false;
}