DEV Community

Cover image for How to style a text using an object and computed property in vue.js
AbdulKareem Alabi
AbdulKareem Alabi

Posted on

How to style a text using an object and computed property in vue.js

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>

Enter fullscreen mode Exit fullscreen mode

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>


Enter fullscreen mode Exit fullscreen mode

Top comments (0)