DEV Community

Nivethan
Nivethan

Posted on

A Vue3 Tutorial - 04 Searching a Table

https://github.com/Krowemoh/vue3-without-build

Now that we fetched our data and displayed it, it's time to add a search bar.

<div v-else>
    <input v-model="searchString" placeholder="search" class="mb-1">
    <table>
    ...
    <table>
</div>
Enter fullscreen mode Exit fullscreen mode

We use the v-model tag to bind a form element to a javascript variable. The variable name searchString in the input tag will correspond with a variable called searchString in our Vue application.

data() {
    return {
        searchString: "",
        workers: [],
    }
},
Enter fullscreen mode Exit fullscreen mode

Now as we type things in or delete things, the variable in the vue application will also be updated. We want our search to happen instantly as the person types, so now we are going to use the computed property of our vue application.

Like the methods property, computed is also a property but functions defined inside this object will be run anytime anything inside the function changes value.

data() {
    ...
},
computed: {
    filteredWorkers() {
        const filteredWorkers = this.searchString === ""
            ? this.workers
            : this.workers.filter(wo => Object.values(wo).join("").indexOf(this.searchString) !== -1);
        return filteredWorkers;
    },
},
methods: {
    ...
}
Enter fullscreen mode Exit fullscreen mode

Here we write a function called filteredWorkers which will reference the searchString variable in our application. We then do a very poor search of this string in the values of our array of objects.

Once we have our list filtered we can then return this array.

Now instead of displaying all of the workers, what we want to display is this filtered list. When the search is blank, we'll then display everything.

    <tr v-for="worker in filteredWorkers">
Enter fullscreen mode Exit fullscreen mode

We can now reference our computed function instead of our workers variable and everything should be good to go!

As we type, out searchString variable is being updated, which in turn will trigger the computed functions that reference searchString to be re-run, which ultimately leads to the table being re-rendered each time we type. Quite magical!

Top comments (0)