Ember 2、在一次计算中处理两个或多个属性属性。如何按搜索文本和类别过滤
Ember 2, Handle two or more properties in just one computed property. How to filter by search text and category
我的代码在这里:
https://ember-twiddle.com/b894cec64a1d78a71e15b642d512cfcf
我需要将此计算 属性: "postsFiltered" 与类别和搜索一起使用,但是当我在 clickCategory() 上更改类别时,我需要重置搜索文本(如果存在)。
但是计算的 属性 已经被调用了?没有?
同样,当我搜索某些内容时,我需要将类别重置为空。
postsFiltered: Ember.computed('category', 'search', function () {
var posts = this.get('posts');
var search = this.get('search');
console.log('computed postsFiltered() with category: ' + this.get('category') + ', search: ' + search);
return posts.filter((item) => item['categoryId'] === this.get('category'));
// or this when I search, but I don't know how to do one or the other:
// return posts.filter((item) => item['name'].includes(search));
})
如何在同一个计算中处理两个属性属性?
您需要在控制器中引入 search:'',
,并将其传递给帖子组件 {{my-posts posts=posts category=category search=search}}
并且您的 clickCategory
应该在点击类别时重置搜索 属性
clickCategory(categoryId) {
this.set('category', categoryId);
this.set('search','');
}
这将确保您遵循 Data Down Actions Up 策略。 twiddle
编辑:
- Ember.computed.filterBy 这里最后一个参数是一个值而不是 属性 名称
- Ember.computed.filter 我们也不能使用它,因为我们还需要包含一个依赖关系
category
- 所以最终实现了我们自己的计算 属性 而不是内置宏,
categoryPosts: Ember.computed('posts.[]','category', function(){
return this.get('posts').filter(post => post.categoryId === this.get('category'));
}),
我的代码在这里:
https://ember-twiddle.com/b894cec64a1d78a71e15b642d512cfcf
我需要将此计算 属性: "postsFiltered" 与类别和搜索一起使用,但是当我在 clickCategory() 上更改类别时,我需要重置搜索文本(如果存在)。
但是计算的 属性 已经被调用了?没有?
同样,当我搜索某些内容时,我需要将类别重置为空。
postsFiltered: Ember.computed('category', 'search', function () {
var posts = this.get('posts');
var search = this.get('search');
console.log('computed postsFiltered() with category: ' + this.get('category') + ', search: ' + search);
return posts.filter((item) => item['categoryId'] === this.get('category'));
// or this when I search, but I don't know how to do one or the other:
// return posts.filter((item) => item['name'].includes(search));
})
如何在同一个计算中处理两个属性属性?
您需要在控制器中引入 search:'',
,并将其传递给帖子组件 {{my-posts posts=posts category=category search=search}}
并且您的 clickCategory
应该在点击类别时重置搜索 属性
clickCategory(categoryId) {
this.set('category', categoryId);
this.set('search','');
}
这将确保您遵循 Data Down Actions Up 策略。 twiddle
编辑:
- Ember.computed.filterBy 这里最后一个参数是一个值而不是 属性 名称
- Ember.computed.filter 我们也不能使用它,因为我们还需要包含一个依赖关系
category
- 所以最终实现了我们自己的计算 属性 而不是内置宏,
categoryPosts: Ember.computed('posts.[]','category', function(){ return this.get('posts').filter(post => post.categoryId === this.get('category')); }),