首页 > 解决方案 > 重置过滤数据Vue.js

问题描述

我需要实现一个按钮,将过滤器放在我的应用程序中。该应用程序是在 Vue 上编写的。过滤器本身已实现,但我不知道如何实现它们的重置。

<template>
  <div id="app">
    <input type="text" v-model="search">
    <select name="sort" v-model="sort">
      <option v-for="option in options" :value="option.value" :label="option.label"></option>
    </select>
    <table>...</table>
  </div>
</template>

<script>
  import goodsList from './api/data';

  export default {
    name: 'app',
    data() {
      return {
        search: '',
        sort: '',
        options: [
          { label: 'Default', value: 'none' },
          { label: 'Brand', value: 'brand' },
          {label: 'Price', value: 'price'}
        ],
        goods: goodsList,
      }
    },
    computed: {
      filteredList() {
        let filteredGoods = this.goods.filter( item => {
          return item.name.toLowerCase().includes(this.search.toLowerCase());
        });
        switch (this.sort) {
          case 'brand':
            filteredGoods.sort((a, b) => a.brand.localeCompare(b.brand));
            break;
          case 'price':
            filteredGoods.sort((a, b) => parseInt(a.price - b.price));
            break;
        }
        return filteredGoods;
      }
    },
  }
</script>

标签: javascriptvue.jsvuejs2vue-componentreset

解决方案


您将需要一个重置功能,它将默认选定值分配,例如:'none' 给 v-model 'sort'。由于它是双向绑定,因此更改 'sort' 变量的值最终将重置所选选项。

新增功能:

resetOptions: function () {  
  this.sort='none';

}

下面的链接 https://jsfiddle.net/RohanPatil/68wced20/9/


推荐阅读