2017-07-19 109 views
0
的阵列

在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) 
    }) 
} 

我该怎么做这项工作?这是一个很好的模式?

+2

为什么要使用Promises? – thanksd

+1

不是我用过的东西,但我觉得这可能是一个很好的用于柯里化的用例。 – SamHH

+1

如果过滤器不是异步的,使用Promise没有意义。您可以使用帮助器'compose'函数来编写函数,如下所述:https://stackoverflow.com/a/44023242/7636961这样您就不需要从每个过滤器都返回一个Promise。 – wostex

回答

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); 
    }