Reputation: 1503
i am creating a rock-paper-scissors mini game with vue and i try to find a way to toggle classes like variables. for example:
<template>
<div id="human">
<div class="text-center">
<div class="h2 mb-5">Human</div>
<!-- PLEASE CHECK BELOW HERE -->
<i class="play-hand far fa-hand-{{ iconName }}"></i>
<!-- OR -->
<i class="play-hand far {{ icon }}"></i>
<div class="h3 mt-4">{{ activeHand }}</div>
<div class="row select-hand mt-4">
<div class="col-md-4">
<i class="far fa-hand-rock" @click="setHand(hands[0])"></i>
</div>
<div class="col-md-4">
<i class="far fa-hand-paper" @click="setHand(hands[1])"></i>
</div>
<div class="col-md-4">
<i class="far fa-hand-scissors" @click="setHand(hands[2])"></i>
</div>
</div>
</div>
</div>
</template>
i marked with a commentary. I am pretty sure you get what i want to do.
I don't want to use document.querySelector()
for this.
<script>
export default {
data: () => {
return {
activeHand: 'Choose a Hand',
hands: [
{
name: 'Rock',
strength: 'scissor',
weakness: 'paper',
icon: 'fa-hand-rock'
},
{
name: 'Paper',
strength: 'rock',
weakness: 'scissor',
icon: 'fa-hand-paper'
},
{
name: 'Scissor',
strength: 'paper',
weakness: 'rock',
icon: 'fa-hand-scissors'
}
]
}
},
methods: {
setHand (hand) {
console.log(hand.name)
this.activeHand = hand.name
console.log(hand.icon)
let playHandSelector = document.querySelector('.play-hand')
playHandSelector.classList.remove(this.activeHand.includes(hand))
playHandSelector.classList.add(hand.icon)
}
}
}
</script>
<style lang="scss">
#human .far {
transform: rotate(90deg);
}
</style>
There must be a vue way to toggle a class dynamically by name. maybe without a true/false toggeling?
Upvotes: 1
Views: 1387
Reputation: 3907
You have to use Vue's v-bind
directive for class bindings and put any variable usage into that markup. Take a look at the documentation here.
Eventually your code could look like this.
<i class="play-hand far" :class="icon"></i>
Keep in mind to use proper class binding syntax in either using objects or arrays.
Upvotes: 3