DEV Community

Nivethan
Nivethan

Posted on

A Vue3 Tutorial - 06 Conditional Styling

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

Now that we have sorting done, let's add a sort icon to the header. Before we do that we should clean up the header as it's starting to get unwieldy. Ideally, we want the header to also be dynamic.

We can update our getWorkers function to also get the headers.

async getWorkers() {
    const workers = [
        { name: "Airi Satou", position: "Accountant", office: "Tokyo", age: 33},
        { name: "Angelica Ramos", position: "Chief Executive Officer (CEO)", office: "London", age: 47 },
        { name: "Cedric Kelly", position: "Senior Javascript Developer", office: "Edinburgh", age: 22 },
        { name: "Jennifer Chang", position: "Regional Director", office: "Singapore", age: 28 },
    ];

    const headers = [
        { key: "name", value: "Name" },
        { key: "position", value: "Position" },
        { key: "office", value: "Office" },
        { key: "age", value: "Age" },
    ];

    this.headers = headers;
    this.workers = workers;
}
Enter fullscreen mode Exit fullscreen mode

Next, we update the data variable to have a headers variable.

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

Finally we can update the html to use our new variable!

<thead>
    <th v-for="header in headers" @click="setSortColumn(header.key)">
        {{header.value}}
    </th>
</thead>
Enter fullscreen mode Exit fullscreen mode

Now that we have that done, we can now add some arrows to show the sort.

<thead>
    <th v-for="header in headers" @click="setSortColumn(header.key)">
        {{ header.value }}
        <span class="arrow" :class="{ active: this.sortColumn === header.key && this.order === 'ASC'}">
            &#8593;
        </span>
        <span class="arrow" :class="{ active: this.sortColumn === header.key && this.order === 'DESC'}">
            &#8595;
        </span>
    </th>
</thead>
Enter fullscreen mode Exit fullscreen mode

Here we are using the unicode characters for the up and down arrows.

We also have :class binding now which will conditionally add a class to an element. In this case, we check to see which column we are sorting on and the order when we set the active flag.

We can also include styling in the html file which will be specific to this component.

<style>
th { cursor: pointer; }
.arrow { color: gray; }
.active { color: black; }
</style>
Enter fullscreen mode Exit fullscreen mode

With that! We have a decent enough header. When we click on a column, we'll see our active class flipping between the two states of ordering and it will also tell us which column we are sorting on.

Top comments (0)