I have been using Vue and Vuetify quite a bit and absolutely loving it. The combination alongside some of the backend Javascript frameworks (like AdonisJS, Strapi) make web app building fast and fun.
In this post let’s take a look at how we can dynamically style elements by using data to drive styling.
An Example with Data tables
One of the common factors in all my data-driven applications is the data table. Looking back one of the primary factors for choosing Vuetify may be its powerful data table. I just need to supply a dataset and with the power of Vue, I have a super user-friendly table.
<template>
<div>
<v-toolbar flat dense>
<v-spacer></v-spacer>
<v-btn outline small @click="viewItemDetail({})">View</v-btn>
</v-toolbar>
<v-data-table
:headers="headers"
:items="records['data']"
:loading="loading"
hide-actions
>
<template slot="items" slot-scope="props">
<tr @click="setActiveRecord(props.item)">
<td>{{ props.item.id }}</td>
<td>{{ props.item.created_at }}</td>
<td>{{ props.item.name }}</td>
<td>{{ props.item.status_cd }}</td>
<td>{{ props.item.description }}</td>
</tr>
</template>
</v-data-table>
</div>
</template>
A typical requirement in a data table is the ability to show users the record that they select for an action.
For e.g. click on record and click ‘Print Report’ button to print a report, or click on record to view details in a detail tab.
Calling an action is quite straight-forward. In the example you will see -
<tr @click="setActiveRecord(props.item)"></tr>
setActiveRecord may be a mutation in vuex.
setActiveRecord(state, value) {
state.activeServiceReq = value;
}
If it is a variable within the component, you could simply do a
<tr @click="this.activeRecord = props.item"></tr>
When user clicks and the activeRecord is set, we want to highlight the record. Change the tr tag to -
<tr
@click="setActiveRecord(props.item)"
:class="{activeRow:activeRecord['id'] == props.item.id}"
></tr>
Include the following style in the component..
<style scoped>
.activeRow {
background-color: rgb(240, 240, 240);
}
</style>
Now click away on the record to glory.
Backgrounds in ’technicolour’
If you want to change the background color of a row in a data table or for another element, we can make the class name dynamic.
<div :class="`background-${status}.toLowerCase()`">
<td>{{ status }}</td>
</div>
And, the style will be -
<style scoped>
.background-inactive {
background-color: rgb(240, 240, 240);
}
.background-inactive {
background-color: rgb(120, 120, 120);
}
</style>
Conclusion
Oh colours.. you just can’t hate them for long.