【问题标题】:Vue 2: Can't Get Past "Cannot Read Property"Vue 2:无法通过“无法读取属性”
【发布时间】:2017-01-15 14:59:16
【问题描述】:

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

“未捕获的类型错误:无法读取 null 的属性“长度” VueComponent.showChoices(评估在(app.js:310), :33:32)”

。我以为我是在用条件来保护它,但这个错误现在已经困扰了我 3 个小时。这是showChoices:

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

【问题讨论】:

  • 您正在测试filtered 并尝试访问search 的长度。所以search 必须为空。
  • search 在数据中本地声明为 search: null。不就是这样吗?
  • 所以你遇到了一个错误,告诉你你有一个空对象,你知道你有一个空对象,然后发布一个问题,为什么你在访问空对象的道具时会出错?我不了解实际问题是什么。
  • 我没有将搜索视为潜在问题,因为我已在组件本地声明它——这只是我的一个盲点。我现在正在使用 search: '' 来声明它,因此它不为 null 并且仍在进行检查。有时,在关注一个问题数小时后,您只需要新鲜的眼光。只要你提到搜索,问题就解决了。感谢您的宝贵时间。
  • 不客气。谢谢。

标签: vue.js vuex


【解决方案1】:

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

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

【讨论】:

  • ...或者简单地将search初始化为一个空数组而不是null
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-01
    • 2023-03-24
    • 2017-04-21
    • 2017-10-10
    • 2020-12-04
    • 2018-07-07
    • 2019-01-30
    • 2017-02-12
    相关资源
    最近更新 更多