Vue Js Change Button Class on Click:In Vue.js, you can change the class of a button element when it is clicked by using the “v-bind” directive along with the “class” attribute.
First, you need to define a data property in your Vue instance that will hold the current class name of the button. Then, you can use the “v-bind:class” directive to dynamically bind a class to the button based on the value of the data property.
To toggle the class of the button when it is clicked, you can add a click event listener to the button and update the data property that holds the class name accordingly.
Overall, this approach allows you to easily toggle the appearance of a button based on user interaction, such as changing its color, shape, or text.
How can you change the class of a button in Vue js when it is clicked?
This code creates a button that toggles between two classes when clicked. The isActive
variable in the data
object is used to keep track of whether the button is currently active or not. The :class
binding in the button element binds the class active
to the button element when isActive
is true
, and removes it when isActive
is false
.
The @click
directive is used to listen for the click event and toggle the isActive
value by setting it to its opposite value using the !
operator.
When the button is active, its background color changes to #00bfff and its text color changes to white. When the button is inactive, it reverts to its default styling with a background color of #f0f0f0 and black text
Vue Js Change Button Class on Click Example
<div id="app">
<button :class="isActive ? 'btn active' : 'btn'" @click="isActive = !isActive">
Click me
</button>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
isActive: false
};
}
});
</script>
<style scoped>
.btn {
padding: 10px 20px;
background-color: #f0f0f0;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s ease;
}
.btn.active {
background-color: #00bfff;
color: #fff;
}
</style>