应用于对象数组的多个过滤器

时间:2017-07-19 15:31:54

标签: javascript vue.js

在其中一个Vue我的组件中,我有一个看起来像这样的代码

<li class="comment" v-for="comment in comments">
  ...
</li>

我的计算方法

computed: {
    comments() {
      // All filter UI elements are associated with a filter method
      // and when the user interacts with an element of the UI, filtersToApply gets populated with
      // the associated method. Not too important right now, 
      // it just checks whether user interacted with the UI or not, so it could essentially be a boolean. But I plan to make use of the functionality at a later time.
      const filtersToApply = this.filtersToApply();

      // if user hasn't interacted with the filter UI, just return the comments
      // else, apply filter(s) to comments
      if (filtersToApply.length === 0) {
        return this.$store.getters.comments;
      } else {
        return this.applyFilters(this.$store.getters.comments);
      }
    }

最终,我想做这样的事情:

// Apply the filters to the comments, one by one
applyFilters(comment) {
  return this.filterByX()
    .then(this.filterByY)
    .then(this.filterByZ)
    ....
}

过滤方法看起来像

filterByX(comments) {
  return new Promise((resolve, reject) => {
    .......
    resolve(comments)
  })
}

我怎么能让这个工作?这是一个好的模式吗?

1 个答案:

答案 0 :(得分:0)

感谢@wostex指出我正确的方向。这就是我所做的(我使用lodash库来实现管道):

将applyFilters功能更改为

applyFilters(filters) {
  const filteredComments = _.flow(filters)
  return filteredComments(this.$store.getters.comments);
}

在计算的注释方法中,我将过滤器数组传递给applyFilters,这是我做的唯一其他更改。

  const filtersToApply = this.filtersToApply();

  if (filtersToApply.length === 0) {
    return this.$store.getters.comments;
  } else {
    return this.applyFilters(filtersToApply);
  }