[Vuejs]-Toggle active class between child components VueJS

0đź‘Ť

That’s where Vue shines. For that you need to ID your tiles so you would know which one isActive at the moment. Something that would differentiate one tile from another.

The best way I can see this problem is. Instead of having isActive: false in Explore it would be better to have activeTile: 1 or activeTile: 'FooTile' and a prop for ToggleTile(id or name, to follow this example, but could be anything)

And in your ToggleTile component emit the event with that prop like:

this.$emit('toggle-active', this.name)
or
this.$emit('toggle-active', this.id)

Back to Explore change the toggleTile function

toggleTile: function (nameOrId) {
  this.activeTile = nameOrId
}


<toggle-tile @toggle-active="toggleTile" :showtile="activeTile === 'FooTile'"></toggle-tile>

<toggle-tile @toggle-active="toggleTile" :showtile="activeTile === 1"></toggle-tile>

The “magic” here is that whenever activeTile change that prop showTile will change showing the active tile and hiding the others.

This is a common way of thinking about when developing in Vue. Say when that condition would be true instead of making the changes when clicking or something like with JQuery.

Leave a comment