Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a search filter with Vue 3 and JavaScript.
Create the Project
We can create the Vue project with Vue CLI.
To install it, we run:
npm install -g @vue/cli
with NPM or:
yarn global add @vue/cli
with Yarn.
Then we run:
vue create search-filter
and select all the default options to create the project.
Create the Search Filter
To create the image slider, we write:
<template>
<div>
<input v-model="keyword" placeholder="search" />
<div v-for="(f, index) of filterImages" :key="index">
<img :src="f.url" />
<p>{{ f.description }}</p>
</div>
</div>
</template>
<script>
const images = [
{
url: "https://images.dog.ceo/breeds/affenpinscher/n02110627_4597.jpg",
description: "affenpinscher",
},
{
url: "https://images.dog.ceo/breeds/akita/Akita_Inu_dog.jpg",
description: "akita",
},
{
url: "https://images.dog.ceo/breeds/retriever-golden/n02099601_7771.jpg",
description: "golden retriever",
},
];
export default {
name: "App",
data() {
return { keyword: "", images };
},
computed: {
filterImages() {
const { images, keyword } = this;
return images.filter(({ description }) => description.includes(keyword));
},
},
};
</script>
<style scoped>
img {
width: 200px;
height: 200px;
}
</style>
In the template, we have the input element.
We bind the input value of it to the keyword reactive property with v-model .
And we add a placeholder for clarity.
Then we loop over the filterImages array and render the image from the url and the description .
We have to set the key to a unique key so that Vue 3 can track the divs rendered by v-for properly.
In the script tag, we have the images array with the data we want to filter.
In the data method, we return the keyword and images properties to make them reactive.
images are from the images array.
Then to add the filter when we’re typing, we create the filterImages computed property with the images that match the keyword we typed in.
We get that by calling the filter method on this.images and check the description to see the this.description reactive property is a substring of the description in the objects in the images array.
Then in the style tag, we make all the img elements display as 200px by 200px to make them fit on the page.
When we type in something into the input box, we should see the matching items displayed.
Conclusion
We can create a search filter easily with Vue 3.