2017-07-19 197 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); 
    }