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>
2. add event listener on the button that will change the value of 'colorMe'
<button @click="colorMe = true">Add Class</button>
3. Define a data property in vue instance named 'colorMe'
export default {
name: "App",
data() {
return {
colorMe: false,
};
},
};
4. Make css class which will be applied after button click
<style scoped>
.change-me {
font-size: 2rem;
}
.color-me {
color: goldenrod;
}
</style>
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>
👉 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>
And thats it.You have done awsome class binding feature of vuejs 😃
See the complete code here Here 🚀
Top comments (1)
with new compositional API we dont have to do default export, can simply define variables like this