[Vuejs]-How to bind a class to child, when parent is clicked in vue js

0👍

Binding dynamic classes and styling to dom elements is described quite extensively already in the documentation, so I recommend reading that.

When working with Vue, think about what states your component can be in. Then figure out when and how you want to change between the states. In your case you have two states:

  1. An element with class "anotherClass" is shown
  2. An element with class "anotherClass" is not shown

How do we toggle between them? Well, we use a data attribute and calculate based on that which classes we need to put on things. We use the shorthand syntax :class="variable" for this with a computed property that adds or removes a class based on a data property that governs if we want to show the element with class "anotherClass".

<template>
  <div class="parent" @click="showDescriptiveNameOfThing = !showDescriptiveNameOfThing">
    <i :class="iconClasses"></i>
    <div :class="descriptiveNameOfThingClasses"></div>
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  data () {
    return {
      showDescriptiveNameOfThing: false
    }
  },
  computed: {
    iconClasses() {
      return {
        asdas: true,
        asd: true,
        rotate: this.showDescriptiveNameOfThing
      }
    },
    descriptiveNameOfThingClasses() {
      return {
        another-class: true,
        show: this.showDescriptiveNameOfThing
      }
    }
  }
</script>

<style>
  .another-class {
    visibility: hidden;
  }

  .another-class.show {
    visibility: visible;
  }

  .asdas.rotate {
    transform: rotate(-90deg);
  }
</style>

On another note (and I already added that as a comment), pretty much anything you could do with jQuery can (and should!) be done with Vue if you are using Vue. Modifying DOM elements that are managed by Vue externally will cause you a lot of headache when an element is changed by Vue and changes from jQuery might be undone, or worse, Vue errors out because the DOM is not as it is supposed to be anymore.

Leave a comment