【问题标题】:Vue.js data objects don't work with some lodash functions?Vue.js 数据对象不适用于某些 lodash 函数?
【发布时间】:2016-08-21 22:32:18
【问题描述】:

我正在做一个小商店模式,如docs所示。

这是我的商店对象:

import Vue from 'vue';
import _ from 'lodash';

class EmployeeService {

  constructor() {
    this.employees = null;
    this.url = 'http://url';
  }

  all() {
    if (this.employees === null) {
      return Vue.http.get(this.url)
        .then(response => (this.employees = response.data.data));
    }

    return new Promise(resolve => resolve(this.employees));
  }

  find(id) {
    const employee = _.find(this.employees, { id });

     if (_.isUndefined(employee)) {
       return Vue.http.get(`${this.url}/${id}`)
         .then(response => response.data);
     }

    return new Promise(resolve => resolve(employee));
  }

}

export default new EmployeeService();

问题出在find(id) 方法中,每当我使用lodash 函数_.find() 时,它总是 返回undefined,即使对象确实存在。但是当我使用 vanilla js 时,像这样:

const employee = this.employees.flter(emp => emp.id == id)[0];

找到对象没有问题。

我想知道为什么会发生这种情况,并确定这是错误还是预期行为。

【问题讨论】:

    标签: javascript lodash vue.js


    【解决方案1】:

    Vue.js 没有问题。但它在您的_.find 中。正如lodash docs _find 所说:

    遍历集合的元素,返回第一个元素谓词返回truthy for。

    在您的代码_.find(this.employees, { id }); 中,{ id } 不会返回真实值。对于谓词参数,您应该使用

    function(o) {
        return o.id == id;
    }
    

    或简写:{'id': id}

    【讨论】:

    • 但我正在这样做,使用 es6 功能 object short-hand{ id: id } == { id }。但无论哪种方式,我在发帖前都按照你说的尝试过,但也没有用
    • 速记时,我的意思是:const employee = _.find(this.employees, { 'id': id });
    • 我确实按照你说的试过了,但是没有用。如果this.employees 仅仅是一个数组,它就可以工作。但是 Vue.js 对它做了一些事情,所以当this.employees 中的数据发生变化时,每个组件都可以更新。
    • 看到这个plunker,在script.js中有一个方法findId1。在这种方法中,_find 效果很好。此外,在您的示例中,EmployeeService 只是一个普通的 ES6 类,与 Vue.js 没什么特别的。对于您的问题,我建议您创建一个 plunker,以便其他人可以帮助您。
    • 原来Lodash在内部使用===操作符,我使用==手动传递谓词参数,一切正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多