2017-12-12 15 views
1

次の計算された関数を持つので、検索入力フィールドに基づいて住宅をフィルタリングします。これは機能します。Vue計算された順序付きフィルタ

computed: { 
    filtered: function() { 
     var self = this; 
     let searchTerm = (this.search || "").toLowerCase() 
     if(this.houses) { 
      return this.houses.filter(function(item) { 
       let city = (item.city || "").toLowerCase() 
       let street = (item.street || "").toLowerCase() 
       return city.indexOf(searchTerm) > -1 || street.indexOf(searchTerm) > -1; 
      }) 
     } 
     } 
    } 

しかし、都市やストリートでも注文を実装する方法は? ascとdescの両方。

これはテーブルです:

<input type="search" v-model="search" placeholder="Search for City OR Street" /> 
<table> 
    <thead> 
     <tr> 
      <th @click="sortByStreet()">Street</th> 
      <th @click="sortByCity()">City</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr v-for="house in filtered"> 
      <td>{{ house.street }}</td> 
      <td>{{ house.city }}</td> 
     </tr> 
    </tbody> 
</table> 

機能sortByStreet()sortByCity()でそれを修正する方法は?フィルタと組み合わせる。

答えて

3

clickは、sortByという変数を設定する必要があります。計算結果を使用して結果のソート方法を決定します。変数が変更されると、計算された値が再計算されます。

new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    search: 'Z-town', 
 
    reverse: false, 
 
    houses: [{ 
 
     street: 'First', 
 
     city: 'Z-town' 
 
     }, 
 
     { 
 
     street: 'Second', 
 
     city: 'A-town' 
 
     }, 
 
     { 
 
     street: 'First', 
 
     city: 'A-town' 
 
     }, 
 
     { 
 
     street: 'Second', 
 
     city: 'Z-town' 
 
     } 
 
    ], 
 
    sortBy: 'street' 
 
    }, 
 
    computed: { 
 
    filtered: function() { 
 
     const result = this.houses 
 
     .filter(entry => [entry.street, entry.city].find(x => x === this.search)) 
 
     .sort((a, b) => 
 
      a[this.sortBy] < b[this.sortBy] ? -1 : a[this.sortBy] !== b[this.sortBy] 
 
     ); 
 
     
 
     return this.reverse ? result.reverse() : result; 
 
    } 
 
    } 
 
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script> 
 
<div id="app"> 
 
    <input type="search" v-model="search" placeholder="Search for City OR Street" /> 
 
    <input type="checkbox" v-model="reverse"> Descending 
 
    <table> 
 
    <thead> 
 
     <tr> 
 
     <th @click="() => sortBy = 'street'">Street</th> 
 
     <th @click="() => sortBy = 'city'">City</th> 
 
     </tr> 
 
    </thead> 
 
    <tbody> 
 
     <tr v-for="house in filtered"> 
 
     <td>{{ house.street }}</td> 
 
     <td>{{ house.city }}</td> 
 
     </tr> 
 
    </tbody> 
 
    </table> 
 
</div>

+0

それはVue1が、NOG Vue2でいるようでした。それとも、あなたは模範を持っていますか? – user1469734

+0

私はスニペットの例を追加しました。 –

+0

素晴らしい!しかし、私はをもう使えません。両方の世界をマージすることについてのこの問題。そしてそれはただの唯一のものです。 – user1469734

関連する問題