wawanopoulos
wawanopoulos

Reputation: 9804

VueJS - Filter elements on list base on search value

In my page, I have a list of elements built from a local variable stored in my component. I added an input text used for search to be able to filter and display only elements for which the name contains the string which is searched by the user.

I never see any refresh on my list with the following code. Where is my mistake ?

TEMPLATE

<input v-model="searchTextValue" v-on:keyup="onSearch" type="text" />

<div v-for="car in localCars" :key="car.id">
    <span>{{ car.name }}</span>
</div>

JS

export default {
    data() {
        return {
            localCars: [{name: "audi"}, {name:"fiat"}],
            searchTextValue : ""
        };
    },
    methods: {
        onSearch() {
            this.localCars.filter(function (car) {
                return car.name.indexOf(this.searchTextValue) !== -1;
            });
        },
    }
}

Upvotes: 4

Views: 10125

Answers (1)

Parag Diwan
Parag Diwan

Reputation: 3956

Your code should look like this: -

Demo Here

<template>
  <div>
    <input v-model="searchTerm" type="text">
    <div></div>
    <div v-for="car in filterByTerm" :key="car.id">
      <span>{{ car.name }}</span>
    </div>
  </div>
</template>


<script>
export default {
  name: "filter-demo",
  data() {
    return {
      localCars: [{ name: "audi" }, { name: "fiat" }],
      searchTerm: ""
    };
  },
  computed: {
    filterByTerm() {
      return this.localCars.filter(car => {
        return car.name.toLowerCase().includes(this.searchTerm);
      });
    }
  },
  methods: {}
};
</script>

Upvotes: 9

Related Questions