Noobmaster
Noobmaster

Reputation: 75

Search bar vue.js

I want to include search bar in vue.js. I am quite new to vue. I need to filter data on the front end. How do I filter the data when I get it in the script section.

Here is my code:

<template>
  <div>
    <div class="search-wrapper panel-heading col-sm-12">
      <input type="text" v-model="search" placeholder="Search" /> <br />
      <br />
    </div>
    <table class="table" id="myTable">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Category</th>
          <th>Quantity</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="product in products" :key="product.id">
          <td>{{ product.id }}</td>
          <td>{{ product.name }}</td>
          <td>{{ product.category }}</td>
          <td>{{ product.quantity }}</td>
          <td>{{ product.status }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      products: []
    };
  }
};
</script>

Upvotes: 5

Views: 16847

Answers (1)

Turtlefight
Turtlefight

Reputation: 10710

A simple way to do this in vue would be to use a computed property that automatically filters your products when the search text changes.

e.g.:

Vue.createApp({
  data() {
    return {
      products: [
        {id: 1, name: "Foo"},
        {id: 2, name: "Bar"},
        {id: 3, name: "Baz"},
        {id: 4, name: "Foobar"}
      ],
      search: ""
    };
  },
  computed: {
    filteredProducts() {
      return this.products.filter(p => {
        // return true if the product should be visible

        // in this example we just check if the search string
        // is a substring of the product name (case insensitive)
        return p.name.toLowerCase().indexOf(this.search.toLowerCase()) != -1;
      });
    }
  }
}).mount('#app');
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  <div class="search-wrapper panel-heading col-sm-12">
    <input type="text" v-model="search" placeholder="Search" /> <br> <br>
  </div>  
  <table class="table" id="myTable">
    <thead>
      <tr>
          <th>ID</th>
          <th>Name</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="product in filteredProducts" :key="product.id">
          <td>{{ product.id }}</td>
          <td>{{ product.name }}</td>
      </tr>
    </tbody>
   </table>
</div>

Upvotes: 5

Related Questions