[Vuejs]-Vuejs toggle class to the body on button click in a components

2๐Ÿ‘

โœ…

You can emit an event inside your header and maybe catch it in the mounted of app component like this:

In your sidebar or other component:

on_some_btn_click: function (){

    this.$emit('toggle_root_class');

}

In your app component:

mounted: function(){

    var _this = this;

    this.$on('toggle_root_class', function(){
             _this.active = !_this.active;
    });

}

Vue may restrict event from being observed in sibling components. So I use EventBus in my projects to handle sending events easily.

๐Ÿ‘คWaleed

2๐Ÿ‘

the problem lies in your component scope. You tried to access data in Header.vue in App.vue which is impossible by the structure in showed in your code. Consider moving isActive data to App.vue or use Vuex.

๐Ÿ‘คEric Marcelino

-1๐Ÿ‘

You can use jquery to toggle class for an element which is not inside the Vue template.
You can call a function on click of a button and inside it, you can toggle class in body tag using jquery.

<template lang="html">
 <header>
  <button class="navbar-toggler navbar-toggler align-self-center" type="button" :class="{ active: isActive }" @click="activeLink">
  <span class="mdi mdi-menu"></span>
  </button>
 </header>
</template>

<script>
export default {
  name: 'app-header',
  data: {
    isActive: false
  },
  methods: {
    activeLink() {
         $('body').toggleClass('.class-name');
    }
  }
}
</script>
๐Ÿ‘คJigar

Leave a comment