styling in vue.js can be done using many ways, but how to use object for class binding seems a bit challenging because all the value in the object get applied at once, here is an example of what i mean π
<template>
<label
><input
type="radio"
name="rating"
value="Bad"
v-model="rating"
/>
Bad</label
><br />
<label
><input
type="radio"
name="rating"
value="Okay"
v-model="rating"
/>
Okay</label
><br />
<label
><input
type="radio"
name="rating"
value="Good"
v-model="rating"
/>
Good</label
>
<p :class="{
bad: 'rating',
okay: 'rating',
good: 'rating',}"
>Rate this page: {{ rating }} </p>
</template>
<script>
export default {
data() {
return {
rating: "",
};
},
};
</script>
<style>
.bad {
color: red;
}
.okay {
color: purple;
}
.good {
color: green;
}
</style>
the method above will work, but the last value which is green styling will only be applied, but if you inspect in the browser you will see all the object properties was applied, that leaves us with wondering while is other styling not applying when we switch to other rating, so how to fix it is to use computed properties π
<template>
<div>
<p :class="activeColor">Rate this page: {{ rating }}</p>
<label
><input
type="radio"
name="rating"
value="Bad"
v-model="rating"
/>
Bad</label
><br />
<label
><input
type="radio"
name="rating"
value="Okay"
v-model="rating"
/>
Okay</label
><br />
<label
><input
type="radio"
name="rating"
value="Good"
v-model="rating"
/>
Good</label
>
</div>
</template>
<script>
export default {
data() {
return {
rating: "",
};
},
computed: {
activeColor() {
return {
bad: this.rating === "Bad",
okay: this.rating === "Okay",
good: this.rating === "Good",
};
},
},
};
</script>
<style>
.bad {
color: red;
}
.okay {
color: purple;
}
.good {
color: green;
}
</style>
Top comments (0)