Vue.js 数据对象不适用于某些 lodash 函数?
Vue.js data objects don't work with some lodash functions?
我正在做一些 存储模式,如 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()
时,它总是returnsundefined
,即使对象确实存在。但是当我使用 vanilla js 时,像这样:
const employee = this.employees.flter(emp => emp.id == id)[0];
找对象没问题
我想知道为什么会发生这种情况,并确定它是错误还是预期行为。
没有Vue.js的问题。但它在您的 _.find
中。正如 lodash docs _find 所说:
Iterates over elements of collection, returning the first element predicate returns truthy for.
在您的代码 _.find(this.employees, { id });
中,{ id }
不是 return 真值。对于谓词参数,您应该使用
function(o) {
return o.id == id;
}
或shorthand:{'id': id}
.
我正在做一些 存储模式,如 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()
时,它总是returnsundefined
,即使对象确实存在。但是当我使用 vanilla js 时,像这样:
const employee = this.employees.flter(emp => emp.id == id)[0];
找对象没问题
我想知道为什么会发生这种情况,并确定它是错误还是预期行为。
没有Vue.js的问题。但它在您的 _.find
中。正如 lodash docs _find 所说:
Iterates over elements of collection, returning the first element predicate returns truthy for.
在您的代码 _.find(this.employees, { id });
中,{ id }
不是 return 真值。对于谓词参数,您应该使用
function(o) {
return o.id == id;
}
或shorthand:{'id': id}
.