2017-07-19 2 views
0

In einem Vue meine Komponenten I Code haben, wie diese letztlichMehrere Filter angewendet Array von Objekten

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

Und meine berechnete Methode

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

aussieht, möchte ich, so etwas tun :

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

, wo die Filtermethoden wie

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

Wie könnte ich das funktionieren lassen? Und ist es ein gutes Muster?

+2

Warum möchten Sie Promises verwenden? – thanksd

+1

Nicht etwas, das ich viel benutzt habe, aber ich denke, das wäre möglicherweise ein guter Anwendungsfall zum Curry. – SamHH

+1

Wenn Filter nicht asynchron sind, ist die Verwendung von Promises sinnlos. Sie können Funktionen einfach mit einer "Compose" -Funktion erstellen, wie hier beschrieben: https://StackOverflow.com/a/44023242/7636961 Auf diese Weise müssen Sie keine Promise von jedem Filter zurückgeben. – wostex

Antwort

0

Danke an @wostex, dass sie mich in die richtige Richtung weisen. Hier ist, was ich getan habe (ich bin die lodash Bibliothek Rohr zu implementieren):

Changed applyFilters Funktion

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

In der berechneten Kommentare Methode ich das Array von Filtern applyFilters vorbei, welche die ist nur andere Änderung, die ich gemacht habe.

const filtersToApply = this.filtersToApply(); 

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