DEV Community

Cover image for How To Bind CSS Class with Vue template
Shuvo
Shuvo

Posted on

How To Bind CSS Class with Vue template

Some time we may need to bind css class conditional in vuejs app.Here you can follow this example to bind css class with vue template.

1. There is button.when we click on it the color of the text will be changed by adding a class

<template>
  <div class="main">
    <p class="p-me color-me">Awsome vue</p>

    <button @click="colorMe = true">Add Class</button>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      colorMe: false,
    };
  },
};
</script>

<style scoped>
.change-me {
  font-size: 2rem;
}

.color-me {
  color: goldenrod;
}
</style>

Enter fullscreen mode Exit fullscreen mode

2. add event listener on the button that will change the value of 'colorMe'

<button @click="colorMe = true">Add Class</button>
Enter fullscreen mode Exit fullscreen mode

3. Define a data property in vue instance named 'colorMe'

export default {
  name: "App",
  data() {
    return {
      colorMe: false,
    };
  },
};
Enter fullscreen mode Exit fullscreen mode

4. Make css class which will be applied after button click

<style scoped>
.change-me {
  font-size: 2rem;
}

.color-me {
  color: goldenrod;
}
</style>

Enter fullscreen mode Exit fullscreen mode

5. Here the awesome part comes.Bind the class like :class and apply with js es6 template literal expression.

 <p :class="`p-me ${colorMe && 'color-me'}`">Awsome vue</p>
Enter fullscreen mode Exit fullscreen mode

👉 You can also toggle class by setting the reverse value of colorMe as value of colorMe.Like below

  <button @click="colorMe = !colorMe">Add Class</button>
Enter fullscreen mode Exit fullscreen mode

And thats it.You have done awsome class binding feature of vuejs 😃

See the complete code here Here 🚀

Top comments (1)

Collapse
 
ajinkyax profile image
Ajinkya Borade • Edited

with new compositional API we dont have to do default export, can simply define variables like this

const colorMe = ref(false)


<template>
 <p :class="`p-me ${colorMe && 'color-me'}`">Awsome vue</p>
 <button @click="colorMe = !colorMe">Add Class</button>
</template>

Enter fullscreen mode Exit fullscreen mode