Search code examples
vue.jsvuejs2booleantoggle

Toggle Boolean like toggling classlist Vue 2


This is in my data:

diceRoll: [{value: null, locked: false,},{value: null, locked: false},{value: null, locked: false}, 
{value: null, locked: false},{value: null, locked: false}],

And want to toggle each time an element (dice) is clicked to locked: true or false.

<button class="dice textHover" v-for="(roll, index) in diceRoll" v-html="cssDice[roll.value]"   
@click="roll.locked = true, $event.target.classList.toggle('active')" :key="index"></button> 

Can I toggle the locked boolean that is in my data the same as the classList?

I tried: $event.target.object.toggle('locked') and some similar ways. But it does not work, also it would be two @click events so I might output it in a wrong format.


Solution

  • Instead of doing your logic right inside of your @click you should do it in a method.

    In your methods add a new method like this:

    methods: {
      diceButtonClick(index, $event) {
        this.diceRoll[index].locked = true;
        $event.target.classList.toggle('active');
      }
    }
    

    Then your button would just be:

    <button 
       class="dice textHover" 
       v-for="(roll, index) in diceRoll" 
       v-html="cssDice[roll.value]"   
       @click="diceButtonClick(index, $event)" // This is the change
       :key="index">
    </button>