[Vuejs]-How to select multiple (dice) buttons in VUE2

1👍

Well I would make a dice array in my data and make each button switch their own

boolean:
diceHeld : {
 die1 : false,
  die2 : false,
die3 : false,
die4 : false,
die5 : false
}

Then your "hold" buttons you just address the die directly with something

@click="diceHeld.die1 = !diceHeld.die1"

You can use the same object to determine if the button should look "selected" or not AND you can just look in this object when rolling to see which dice you need to reroll.


Edit 1:
Note this isnt the complete solution you’re looking for but it works and should point you in a working direction.

You could make the HTML like this

<div>
    <div class="die" v-for="diceNumber in numberOfDice" :style="{'background-color' : selectedDiceObject['dice' + diceNumber] ? 'red' : 'green'}" @click="toggleDice(diceNumber)">{{diceNumber}}</div>
</div>

and the JS part like this:

{
  el: '#vueApp',
  data: function () {
    return {
      numberOfDice: 5,
      selectedDiceObject: { dice1: false, dice2: false, dice3: false, dice4: false, dice5: false  }
    };
  },
  methods: {
    toggleDice: function (diceNum) {
      this.selectedDiceObject['dice' + diceNum] = !this.selectedDiceObject['dice' + diceNum];
    }
  },
};

Notice that the dice-buttons background-color is set to reflect its state


Edit2:
Now that the blood has started flowing back to my brain from my stomac I think I would solve it in a slightly different manner:

Html :

<div v-if="selectedDiceObject">
    <div class="die" v-for="dob in selectedDiceObject" :style="{'background-color' : dob.selected ? 'red' : 'green'}" @click="dob.selected = !dob.selected">{{dob.result}}</div>
</div>
<button @click="roll">roll</button>

JS:

{
  el: '#vueApp',
  data: function () {
    return {
      numberOfDice: 5,
      selectedDiceObject: null
    };
  },
  methods: {
    roll: function () {
      for(dicekey in this.selectedDiceObject) {
        if (!this.selectedDiceObject[dicekey].selected)
        this.selectedDiceObject[dicekey].result = Math.round( (Math.random() * 5) + 1);
      }
    }
  },
  mounted: function () {
    let workObj = {};
    for (let i = 1; i <= this.numberOfDice; i++) {
      workObj['dice' + i] = { selected : false, result : 0 };
    }
    this.selectedDiceObject = workObj;
  }

};

Notice here, I use the dice object to hold both the current roll and wether it is selected. This way I can use the same for to control all aspecte of every single dice without much more code.

One of the new things is that I initialize the dice in the mounted event. I could as well fetch data from a server here, but now its completely dynamic. Just set another numberOfDice and viola.. You now work with that number of dice.

Leave a comment