Vue Search Filter

Search filter in Vue JS / Nuxt JS

In our Vue page lets create a search field and for loop to iterate over Avenger’s quotes. The demo is available here on stackblitz

[code language=”html”]
<div class="container">
<div class="row mt-3">
<div class="col">
<h1>Avengers Quotes</h1>
</div>
</div>
<div class="row mt-1">
<div class="col">
<input type="search" id="searchAvenger" class="form-control" v-model="search" placeholder="Search Avenger" />
</div>
</div>
<div class="row mt-2" v-for="avenge in filteredAvenger">
<div class="col-4 text-dark"><h5>{{ avenge.actor }}</h5></div>
<div class="col bg-primary text-light">{{ avenge.quote }}</div>
</div>
</div>
[/code]

Now lets create a data object to search from and a computed property to filter the object

[code language=”html”]
data: () => ({
search: "",
avengers: [
{ actor: "Steve Rogers", quote: "Whatever it takes" },
{ actor: "Thor", quote: "I am still worthy" },
{
actor: "Natasha Romanoff",
quote: "I dont judge people by their worst mistakes"
},
{ actor: "Thanos", quote: "I am… inevitable" }
]
}),
computed: {
filteredAvenger() {
return this.avengers.filter(avenge => {
return (
avenge.actor.toLowerCase().includes(this.search.toLowerCase()) ||
avenge.quote.toLowerCase().includes(this.search.toLowerCase())
);
});
}
}
[/code]

Vue Search Filter

Leave a Reply