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

Add background color when click a button vue js

我正在使用不同的组件使用 VUE JS 构建应用程序。

在其中一个中,我有一个按钮,我希望在单击它时更改颜色。此按钮从 table 中选择不同的项目,因此当我按下该按钮时,我希望该按钮的背景变为红色,例如以了解我单击了哪些项目。

<template>
  <button class="mdc-icon-button material-icons"  @click="doMultiple">delete_outline</button>  
</template>

这是按钮。如何在点击按钮时添加样式?

提前致谢!

您可以使用条件绑定向元素动态添加 class。

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>

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

这是我用watch方法将js变量链接到vue js的版本。这是即时的,并且会随着您沿着颜色选择器拖动光标而改变。检查下面的代码片段。 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>