DEV Community

Nivethan
Nivethan

Posted on

A Vue3 Tutorial - 05 Sorting

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

Now that we have searching done, the next step is to add sorting. We're going to use the same logic from before. We want to be able to click on a header and update a sortColumn variable which will in trigger a new compute. We can actually use our filteredWorkers function as we want the search and sort to stack on top of each other.

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

We also want to keep track of the order as we want to reverse the sort if someone clicks the same header twice.

Now the next step is to add our click events.

<thead>
    <th @click="setSortColumn('name')">Name</th>
    <th @click="setSortColumn('position')">Position</th>
    <th @click="setSortColumn('office')">Office</th>
    <th @click="setSortColumn('age')">Age</th>
</thead>
Enter fullscreen mode Exit fullscreen mode

The @ is a shorthand for the v-on:click which binds the event to a function. We are going to run a function called setSortColumn passing in the column's name.

methods: {
    setSortColumn(column) {
        if (this.sortColumn === column) {
            this.order = this.order === "ASC" ? "DESC" : "ASC";
        } else {
            this.order = "ASC";
            this.sortColumn = column;
        }
    },
    ...
}
Enter fullscreen mode Exit fullscreen mode

We put the setSortColumn in the methods section instead of the computed section because this is something we want to manually control.

Here is also where we have logic that checks to see what the current sortColumn is before changing the ordering of the results.

Now we have everything ready to actually implement our sort!

computed: {
    filteredWorkers() {
        const filteredWorkers = this.searchString === ""
            ? this.workers
            : this.workers.filter(wo => Object.values(wo).join("").indexOf(this.searchString) !== -1);

        const column = this.sortColumn
        const order = this.order;

        filteredWorkers.sort(function(a, b) {
            var nameA = a[column]+"".toUpperCase();
            var nameB = b[column]+"".toUpperCase();
            if (order === "DESC" && nameA > nameB) {
                return -1;
            }
            if (order === "DESC" && nameA < nameB) {
                return 1;
            }
            if (nameA < nameB) {
                return -1;
            }
            if (nameA > nameB) {
                return 1;
            }
            return 0;
        });

        return filteredWorkers;
    },
},
Enter fullscreen mode Exit fullscreen mode

We do our filtering first with our search string. We then run our sort function and our ordering of the results. With that we are done!

We have now wired up our sort to work when we click the headers and we can also search as well.

Top comments (0)