Skip to content
Advertisement

How to impliment getter/setter for each button’s value inside vuetify v-btn-toggle?

I have a vuetify v-btn-toggle like this:

    <v-btn-toggle
      v-model="toggle_values"
      dense
      multiple
    >
      <v-btn value="A">
        A
      </v-btn>
      <v-btn value="B">
        B
      </v-btn>
      <v-btn value="C">
        C
      </v-btn>
    </v-btn-toggle>

But the binding v-model is an array. How could I trigger individual toggled event for buttons A, B, C like this:

data() {
  return { toggle_values: [] }
},
computed: {
  stateA: {
    get() {
      // get A value from other place
    },
    set(isPressed) {
      // do something on A value changed
    }
  },
  stateB: {
    get() {
    },
    set(isPressed) {
    }
  },
  stateC: {
    get() {
    },
    set(isPressed) {
    }
  },
}

Advertisement

Answer

We have to create one method to read the state of buttons and other to set the state, all operations take place in the toggle_values.

data() {
  return { toggle_values: [] }
},
methods: {
  getToggleStateIsPressed: function (value) {
    return this.toggle_values.indexOf(value) === -1 ? false : true;
  },
  setToggleState: function (value, press) {
    if (press && this.toggle_values.indexOf(value) === -1) {
      this.toggle_values.push(value);
    } else if (!press) {
      this.toggle_values = this.toggle_values.filter((val) => {
        return val != value;
      });
    }
  },
},
computed: {
  stateA: {
    get() {
      return this.getToggleStateIsPressed("A");
    },
    set(isPressed) {
      this.setToggleState("A", isPressed);
    },
  },
  stateB: {
    get() {
      return this.getToggleStateIsPressed("B");
    },
    set(isPressed) {
      this.setToggleState("B", isPressed);
    },
  },
  stateC: {
    get() {
      return this.getToggleStateIsPressed("C");
    },
    set(isPressed) {
      this.setToggleState("C", isPressed);
    },
  },
},

If you want to play with the values and see they changing, add this:

Model: {{ toggle_values }} <br />
A is pressed {{ getToggleStateIsPressed("A") }}<br />
B is pressed {{ getToggleStateIsPressed("B") }}<br />
C is pressed {{ getToggleStateIsPressed("C") }}<br />
<v-btn @click="stateA = !stateA">{{ getToggleStateIsPressed("A")?'unpress':'press' }} A</v-btn>
<v-btn @click="stateB = !stateB">{{ getToggleStateIsPressed("B")?'unpress':'press' }} B</v-btn>
<v-btn @click="stateC = !stateC">{{ getToggleStateIsPressed("C")?'unpress':'press' }} C</v-btn>

Hope it helps! 😉

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement