2016-10-14 132 views
1

是的,這是我的一次。我試圖根據一個字符串數組來過濾一個數組。所以,當一個字符串過濾器很容易與Vue公司...Vue JS使用數組來過濾另一個數組?

<div v-for="item in items | filterBy 'words' in 'property'">

...多個搜索字符串變得更加複雜。已經有幾個關於如何在StackOverflow上做到這一點的問題,但答案很少。目前我正在嘗試爲我的需要重新定義自定義篩選器here,但它不起作用。

我的使用情況: 我有組陣列(複選框),用戶可以選擇要過濾的人的數組。每個人被分配到一個或多個組,因此,如果任何其中一個組被用戶選中,則該人應該出現。

所以我的模板是這樣的:

<template v-for="group in ensemble_groups"> 
     <input name="select_group[]" id="[email protected]{{ $index }}" 
     :value="group" 
     v-model="selected_groups" 
     type="checkbox"> 
     <label for="[email protected]{{ $index }}">@{{ group }}</label> 
    </template> 

    <template v-for="person in cast | filterBy selectGroups"> 
     <div>@{{ person.actor_name }}</div> 
    </template> 

你看我的自定義過濾器selectGroups呢?這裏是我的Vue陣列:

selected_groups: [], 
    ensemble_groups: ["Leads","Understudies","Children","Ensemble"], 

    cast: [ 
    { 
     actor_name: "Dave", 
     groups: ["Leads"], 
    }, 
    { 
     actor_name: "Jill", 
     groups: ["Leads"], 
    }, 
    { 
     actor_name: "Sam", 
     groups: ["Children","Ensemble"], 
    }, 
    { 
     actor_name: "Austin", 
     groups: ["Understudies","Ensemble"], 
    }, 
    ], 

最後,這裏是自定義過濾器。我不知道它是否被觸發,因爲當我點擊一個組複選框時,沒有任何反應。

filters: { 
    selectGroups: function() { 
    if (!selected_groups || selected_groups.length === 0) { 
     return cast; 
    } 
    return this.recursiveFilter(cast, selected_groups, 0); 
    } 
}, 
methods: { 
    recursiveFilter: function(cast, selected_groups, currentPosition) { 
    if (currentPosition+1 > selected_groups.length) 
     return cast; 
    var new_cast; 
    new_cast = cast.filter(function(person) { 
     for (group of person.groups) { 
     if (group.value == selected_groups[currentPosition]) 
      return true; 
     } 
    }); 
    return this.recursiveFilter(new_cast, selected_groups, currentPosition+1); 
    } 
} 

因此,如果用戶選擇Leads只有Dave和吉爾應該會出現。如果用戶然後檢查Children,Dave,Jill和Sam應該出現。我很親密!

+0

我會愛是一個filterBy修改器類似於'