[Vuejs]-Filtering table on the frontend โ€“ Vue.JS

0๐Ÿ‘

var app = new Vue({
  el: '#app',
  data: {
    firstNameSearch: "",
    lastNameSearch: "",
    studentIDSearch: "",
    studentsList: [
      {
        firstName: "Dan",
        lastName:"Ramsey",
        studentID: "1",
      },
      {
        firstName: "Jenna",
        lastName:"Combs",
        studentID: "2",
      },
      {
        firstName: "Jill",
        lastName:"Barron",
        studentID: "3",
      },
    ],
  },
  computed: {
    filteredStudentList: function() { 
      let filteredStudents = this.studentsList;
      if (this.firstNameSearch && this.firstNameSearch.lenght != 0) {
        filteredStudents = filteredStudents.filter( student => {
          return student.firstName.search(this.firstNameSearch) != -1;
        })
      }

      if (this.lastNameSearch && this.lastNameSearch.lenght != 0) {
        filteredStudents = filteredStudents.filter( student => {
          return student.lastName.search(this.lastNameSearch) != -1;
        })
      }

      if (this.studentIDSearch && this.studentIDSearch.lenght != 0) {
        filteredStudents = filteredStudents.filter( student => {
          return student.studentID === this.studentIDSearch;
        })
      }
      return filteredStudents;
    }
  },
})
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <table>
    <th>firstnamne</th>
    <th>lastname</th>
    <th>id</th>
    <tr v-for="student in filteredStudentList">
      <td>{{ student.firstName }}</td>
      <td>{{ student.lastName }}</td>
      <td>{{ student.studentID }}</td>
    </tr>
    <label for="firstNameSearch">First name</label>
    <input id="firstNameSearch" type="text" v-model="firstNameSearch"/>
    <label for="lastNameSearch">Last name</label>
    <input id="lastNameSearch" type="text" v-model="lastNameSearch"/>
    <label for="studentIDSearch">ID</label>
    <input id="studentIDSearch" type="text" v-model="studentIDSearch"/>
  </table>
</div>

I think this is an easier approach.
Edited with a snippet.

Leave a comment