首页 > 解决方案 > 在单击时保持按钮颜色直到新单击

问题描述

我需要选择多个在点击时动态显示的按钮。单击的每个按钮都需要更改颜色。再次单击的任何按钮都需要返回旧颜色。我不能使用任何 HTML 属性回调或 Jquery。这只能使用样式标签、引导​​程序或 vue。谁能帮帮我吗?

当前设置:

 <div>
                  <button class="btn btn-success" v-on:click="filterAll" style="margin:2px;">ALL</button>

                  <div class="btn-group btn-group-toggle"  v-for="gen in genreArr"   data-toggle="buttons">
                      <button  class="btn btn-warning"  v-on:click="filterOne(gen)"  style="margin:2px;">{{gen}}</button>

                  </div>

 </div>

老实说,如果有人能告诉我如何用一个按钮做到这一点,那将会很有帮助。

标签: javascripthtmlvue.jsbuttonbootstrap-4

解决方案


假设btn-warningclass 有color: red并且ten-successclass 有color: green. 现在单击按钮,您可以在这些类之间切换。

维护一个数组以包含每个按钮的布尔值

data() {
 return {
   clickBools = [false, false, false, false....], // upto number of genres
   // other attributes
 };
}

和一个方法

methods: {
 filterOne(index) {
  this.clickBools[index] = !this.clickBools[index];
 }
}

并在模板中,进行以下更改

 <div>
                  <button class="btn btn-success" v-on:click="filterAll" style="margin:2px;">ALL</button>

                  <div class="btn-group btn-group-toggle"  v-for="(gen, index) in genreArr"   data-toggle="buttons">
                      <button  :class="['btn', {'btn-warning': !clickBools[index], 'btn-success': clickBools[index]}]"  v-on:click="filterOne(index)"  style="margin:2px;">{{gen}}</button>

                  </div>

 </div>

推荐阅读