Add background color when click a button vue js
10,563
Solution 1
You can use conditional binding to dynamically add a class to an element.
https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: "#app",
data: {
deleteClicked: false
},
methods: {
onClick() {
this.deleteClicked = true;
}
}
})
.red {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div :class="{ red : deleteClicked }">
Item
<button @click="onClick">
Delete
</button>
</div>
</div>
Solution 2
Call the css class with either of the option
.mdc-icon-button material-icons:active{
background:red;
}
OR
.mdc-icon-button material-icons:focus{
background:red;
}
Author by
Multi
Updated on June 04, 2022Comments
-
Multi almost 2 years
I'm building an app with VUE JS, using different components.
In one of them, I have a button that I would like that change the color when I click on it. This button is choosing different items from a table, so when I press that button I want that the background of that button change to red for example to know which ones I have clicked.
<template> <button class="mdc-icon-button material-icons" @click="doMultiple">delete_outline</button> </template>
This is the button. How can I add there the style when button be clicked?
Thanks in advance!
-
Pranav Kale over 4 yearsPlease go through Vue class and style bindings. vuejs.org/v2/guide/class-and-style.html
-
Ramki over 4 yearsYou can do this by adding a class conditionally on click of that button. <button class="mdc-icon-button material-icons" :class="{ bg-red: clicked }">clickme</button> clicked value will be initially false and set it to true on click.
-
Multi over 4 years@Ramki Thanks, but I have tried what you said and it returns me an error on :class because it says that it require an attribute value.
-
-
Multi over 4 yearsThanks, not exactly what I was looking for but that can help me. Thanks Pierre!!
-
Tom N Tech almost 4 yearsAnd what about the original class? How do you preserve it in the element?
-
Pierre Said almost 4 years@rjurney You can have both static classes and dynamic classes
<div class="static" :class="{ dynamic : true }">
vuejs.org/v2/guide/class-and-style.html#Object-Syntax