【问题标题】:vue.js - Cannot read property 'toLowerCase' of undefinedvue.js - 无法读取未定义的属性“toLowerCase”
【发布时间】:2016-11-26 18:09:15
【问题描述】:

我正在过滤具有如下计算属性的项目:

filtered_projects() {
    return this.projects.filter( (project)  =>  {
        return project.title.toLowerCase().indexOf(this.project_filter.toLowerCase()) !== -1
    })
}

当我使用这个添加一个新项目时

submitNewProject() {
   let path = '/api/projects';
   Vue.http.post(path, this.project)
       .then( (rsp) => {
          this.projects.push(rsp.data);
          this.project = this.getSingleProject();
          this.create_project = false;
          return true;
    });
 }

这给了我一个我找不到的错误

TypeError:无法读取未定义的属性“toLowerCase”

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    可能只是您没有正确地将项目数据传递给项目数组。

    首先 vue-resource 现在使用 body 而不是数据来获取响应,因此您可能需要使用:

    this.projects.push(rsp.body)
    

    那么这将为您提供一个数组项,其中包含所有看起来不像您想要的项目。我相信你会追求:

    this.projects = rsp.body
    

    假设响应主体是一个对象数组,这将允许:

    this.projects.filter(project => {})
    

    按预期工作。意思是 project.title 现在应该是有效的

    编辑

    对于要设置为小写的项目标题,您必须返回一个带有标题参数的对象,即

    rsp.body = {
      title: 'FOO',
    }
    

    然后您将通过以下方式在项目数组上设置:

    this.projects.push(rsp.body)
    

    所以首先要解决的是您的响应,对端点进行排序,使其返回您所期望的,然后上述代码的其余部分应该可以工作

    【讨论】:

    • this.projects.push(rsp.body) 没有改变错误。
    • this.projects = rsp.body 创建了一个新错误“TypeError: this.projects.filter is not a function”
    • 响应是什么样的?它是一个对象还是一个数组或多个对象?
    • 是的,.filter 只能对数组起作用——这就是你所拥有的吗?
    • 能把回复的内容发一下吗
    【解决方案2】:

    您需要在 Vue.http.post (self=this) 之前保留“this”,然后在回调中将 this.projects 更改为 self.projects。 解释: How to access the correct `this` context inside a callback?

    【讨论】:

    • 我认为 => 语法改变了这一点
    猜你喜欢
    • 2021-11-28
    • 2020-07-23
    • 2020-06-24
    • 2018-10-23
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2018-08-07
    相关资源
    最近更新 更多