使用 Vue 的搜索框和复选框过滤器

2022-01-25 00:00:00 javascript vue.js vue-component vuejs2

我正在尝试使用 Vue 构建过滤系统.

I am trying to build filter system with Vue.

过滤器工作,但计算的所有函数都是单独的函数.那么我怎样才能使它们成为一个功能并使用它.

Filters working, but all the functions computed are separeted functions. So How can I make those in one function and use it.

export default {

    data() {
        return {
            estates: [],
            search: '',
            regions:['関西','関東','京橋'],
            checkedRegions:[]
        }
    },
    created(){
        axios.get('/ajax').then((response) => {
            this.estates = response.data;
        });
    },
    computed: {
        one: function() {
            var result =  this.estates.filter((estate) =>
                estate.building_name.match(this.search)
            );
            if(this.checkedRegions.length && this.checkedRooms.length) {
                return result.filter(estate => this.checkedRegions.includes(estate.region) && this.checkedRooms.includes(estate.rooms))
            }
            return result;
        }
    }
}

<div class="container-fluid">
        <div class="row">
            <div class="col-md-9">
                <input type="text" v-model="search" name="" placeholder="search estate" value="">
                <div v-for="estate in filteredestate" class="card-body">
                    <h2>{{estate.building_name}}</h2>
                    <p>{{estate.address}}</p>
                </div>
            </div>
        </div>
    </div>

filteredestate filteredRegionsfilteredRooms 构成一个功能.例如如何用 && 返回那些函数?并在这个 div 中使用它.

filteredestate filteredRegions and filteredRooms make one function. for example how to return those function with && ? And use it in this div.

<div v-for="estate in oneFunction" class="card-body">

推荐答案

先将你的过滤搜索结果设置为变量,你可以通过or(||)表达式检查过滤!

Set your filter search result first as variable and you can check filter by or(||) expression !

我通过设置该变量修改了箭头函数内部的 this 并在最后一行返回 result 作为默认值

I modified this inside arrow function by setting to that variable and on the last line return result as default

one: function() {
  var that = this;
  var result =  this.estates.filter((estate) =>
    estate.building_name == that.search;
  );
  if(this.checkedRegions.length || this.checkedRooms.length) {
    return result.filter(estate => that.checkedRegions.includes(estate.region) || that.checkedRooms.includes(estate.rooms))
    }
  // when region and room length is 0
  return result;
  }
}

相关文章