Home > other >  How to remove active classes from all buttons before making another one active?
How to remove active classes from all buttons before making another one active?

Time:09-02

I'm new to vue, I still don't understand everything, tell me. I have buttons that I display through v-for, I need to get the active class of only one button when pressed, all the others need to be turned off, tell me, preferably visually, how can I do it better? I am using the method activeBtn, but this doesn't turn off the active class from the previous buttons

activeBtn(event, index) {
          this.buttons[index].isActive = !this.buttons[index].isActive;
<script>
    data() {
        return {
            buttons: [
              {
                label: "A",
                isActive: false,
                type: "border-left",
                name: "BorderLeftComonent",
              },
              {
                label: "A",
                isActive: false,
                type: "text-balloon",
                name: "TextBalloonComponent"
              },
              {
                label: "A",
                isActive: false,
                type: "dashed",
                name: "DashedComponent"
              },
        ],
        };
    },
    methods: {
        activeBtn(event, index) {
          this.buttons[index].isActive = !this.buttons[index].isActive;
    }
</script>
<template>
      <div id="btn-box">
        <button
          v-for="(button, index) in buttons"
          :key="index"
          :
          @click="component = button.name, activeBtn($event, index)">
        <div :>{{ button.label }}</div>
      </button>
      </div>
</template>

CodePudding user response:

Since you only want to get one active button at any one point, it doesn't make sense to manage the active state inside each button. Instead, you should manage it at group level by storing the currently selected button's id. A button would then be active when its id matches the currently selected id.

Here's an example:

new Vue({
  el: "#app",
  data: () => ({
    buttons: [
      {
        id: "button-1",
        label: "A",
        type: "border-left",
        name: "BorderLeftComonent"
      },
      {
        id: "button-2",
        label: "A",
        type: "text-balloon",
        name: "TextBalloonComponent"
      },
      {
        id: "button-3",
        label: "A",
        type: "dashed",
        name: "DashedComponent"
      }
    ],
    activeButtonId: "button-1"
  }),
  methods: {
    activate(id) {
      this.activeButtonId = id;
    }
  }
});
.on {
  background-color: red
}

.off {
  background-color: blue
}

.on, .off {
  color: white;
}
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<div id="app">
  <div>
    <button
      v-for="(button, index) in buttons"
      :key="index"
      :
      @click="activate(button.id)"
    >
      <div :>{{ button.label }}</div>
    </button>
  </div>
</div>

  • Related