How to do instant filter using vuejs and typescript

Suppose you have a grid/ table and you need filter the items in the table based on the input text you enter in the search field. This can be achieved very easily using vuejs


Your input field should look like this
 <input type="text" v-model="filterKey" 
 placeholder="please type the inventroy name you wish to search" />
Here in v-model we are binding the filter key so we can pass that value to the filter method for filtering

You can load the data to the table either using the hard coded models/from your backend apis
Your table should look like this
<table>
   <thead>
   <tr>
     <th v-for="(header,index) in Header" :key="index">
      {{header.name}}
     </th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="(data, index) in Filter" :key="index" >
      <td>{{data.name}}/td>
      <td>{{}}</td>
      <td>{{}}</td>
    </tr>
  </tbody>
</table> 
Here the Filter  method in the tr v-for is a computed property it will fetch the filtered data.

public get Filter() {
  if (this.filterKey.length > 0) {
  let data: any = [];
  data =  this.data.filter((rowItem: any) => {
   return rowItem.name.toLowerCase().indexOf(this.filterKey.toLowerCase()) !== -1;
  });
  return data;
  } else {
  return this.data;
  }
}
Here the this.data is the grid data needs to be loaded from api  or hard coded one. I am loading it from the backend api call so not adding it here.

The filter input what user enters we are comparing with each array items and checking if it exists then returning it.

0 comments: