DEV Community

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

Posted on

7 3

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 πŸš€

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay