首页 文章

Vue计算滤波器与订购相结合

提问于
浏览
1

我有以下计算功能,所以根据搜索输入字段过滤我的房屋 . 这很有效 .

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() 修复它?结合过滤器 .

1 回答

  • 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>
    

相关问题