简体   繁体   English

单击按钮时添加背景颜色vue js

[英]Add background color when click a button vue js

I'm building an app with VUE JS, using different components.我正在使用不同的组件构建一个带有 VUE JS 的应用程序。

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!提前致谢!

You can use conditional binding to dynamically add a class to an element.您可以使用条件绑定将类动态添加到元素。

https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax https://v2.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>

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;
}

This is my version of linking js variables to vue js with watch method.这是我使用 watch 方法将 js 变量链接到 vue js 的版本。 This is immediate and will change as you drag the cursor along the color picker.这是即时的,并且会随着您沿颜色选择器拖动光标而改变。 Check the code snippet below.检查下面的代码片段。 CSS is also required.还需要 CSS。

 let vue = new Vue({ el: "#view", data: { bg: "#FFFFFF", color: "#000000", }, watch: { bg: css_variable_watcher("--bg"), color: css_variable_watcher("--color"), }, }); //Watcher for CSS function css_variable_watcher(name, suffix = "") { return { immediate: true, handler(new_value, old_value) { document.documentElement.style.setProperty(name, new_value + suffix); }, }; }
 body { background-color: var(--bg); color: var(--color); }
 <body> <div id="view"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <input type="color" v-model="bg"> <input type="color" v-model="color"> <button type="button" v-on:click="[color, bg] = [bg, color]">Swap Text and Background Color</button> <p>Hello. I am a Paragraph. Select the first input to change bg color and second input to change text color.</p> </div> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM