【问题标题】:Search multiple fields in a table in Vue.js with different v-model使用不同的 v-model 在 Vue.js 中的表中搜索多个字段
【发布时间】:2019-10-06 23:38:14
【问题描述】:

我是 vue.js 的新手。我试图使用多个搜索字段过滤表列。对于表中的不同列,我有不同的搜索字段及其各自的 v 模型。我想为每一列启用搜索

我尝试了以下解决方案: 1.Vue.js filterBy to search in multiple fields 2.How do I search through multiple fields in Vue.js 2

使用上述两种解决方案,我想出了这个:

<p>
  <label>First Name</label>
  <input  type="text" placeholder="Enter firstname" v-model="First" />
</p>

<p>
  <label>Last Name</label>
  <input type="text" placeholder="Enter the last Name" v-model="Last" />
</p>

<p>
  <label>CustomerId</label>
  <input type="text" placeholder="Enter the CustomerId" v-model="CustomerId" />
</p>


<table id="clients">
  <thead>
    <tr>
      <th width="40%">First Name</th>
      <th width="20%">Last Name</th>
      <th width="20%">CustomerId</th>
    </tr>
  </thead>

  <tbody v-for="customer in filteredCustomers.slice(0,20)">

    <tr>
      <td>{{customer.first}}</td>
      <td>{{customer.last}}</td>
      <td>{{customer.id}}</td>

    </tr>

  </tbody>
</table>

脚本:

export default {
props:['showMod'],

data() {

return {
  id: '',
  First: '',
  Last: '',
  CustomerId: '',
  categories: []
}
},

computed: {

  filteredCustomers: function () {
    var self = this;
    return this.categories.filter(function (cust) {
      return cust.first.toLowerCase().indexOf(self.First.toLowerCase()) >-1 || cust.last.toLowerCase().indexOf(self.Last.toLowerCase()) >-1
  });
  }

我更改了代码以仅在一个字段上启用搜索,它可以工作,但在尝试搜索多个字段时停止工作。 我不知道我在这方面做错了什么。

编辑: 通过添加“if”,我能够让这些搜索独立工作

  filteredCustomers: function () {
    var self = this;
    return this.categories.filter(function (cust) {
   if (self.First) {
      return cust.first.toLowerCase().indexOf(self.First.toLowerCase()) > -1
   }
    if (self.CustomerId) {
       return cust.clientId.toLowerCase().indexOf(self.CustomerId.toLowerCase()) > -1 
   }

   return cust.last.toLowerCase().indexOf(self.Last.toLowerCase())>-1 
  });

但是,我无法让两个过滤条件同时工作,例如先根据名字进行搜索,然后再根据姓氏进行搜索。

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    你只需要调整逻辑:

    filteredCustomers() {
        return this.categories.filter(customer => {
            return (!this.First || customer.first.toLowerCase().includes(this.First.toLowerCase()))
                && (!this.Last || customer.last.toLowerCase().includes(this.Last.toLowerCase()))
        });
    

    如果您不想麻烦小写转换,也可以使用正则表达式和.match()

    【讨论】:

      猜你喜欢
      • 2015-09-18
      • 2019-05-07
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      相关资源
      最近更新 更多