Thiwanka Dodanwela
Thiwanka Dodanwela

Reputation: 487

How can I change class depending on child component function call in Vuejs

I'm new to Vuejs and I found this issue when i'm trying to do the hamburger menu function.

To get simplify I have added code spinets below

App.vue

<keep-alive>        
    <div class="body-wrapper" v-bind:class="menuOpenCls">
         <div class="hamburger-wrapper" v-on:click="mobileMenu()">
              <div class="hamburger-menu">
                   <span></span>
                   <span></span>
                   <span></span>
                   <span></span>
               </div>
          </div>        
     <router-view v-bind:headerMenu="headerMenu" v-bind:footerMenu="footerMenu" v-bind:ShowSmileys="ShowSmileys"></router-view>
     </div>
</keep-alive>

...

data() {
    return {
        menuOpen:''
    }
},

...

methods: {
      mobileMenu: function() {
          this.menuOpen = !this.menuOpen;
      }
}

...

computed:  {
    menuOpenCls: function() {
        return this.menuOpen ? 'menuopen' : '';
    }    
}

Header.vue

<header>        
        <nav v-if="headerMenu"> 
           <ul class="menu">    
               <li><router-link v-bind:to="item.Url" exact v-on:click="**<<function to change class on App.vue>>**>{{item.Name}</router-link></li>
           </ul>    
        </nav>      
</header>

I want to change (toggle) class name on App.vue (class where body-wrapper is in) depending on click event in Header.vue menu link. How can I achieve this. Can Any one help?

Upvotes: 0

Views: 1490

Answers (1)

gvk
gvk

Reputation: 466

As I understand it, you are trying to pass data between components that are not necessarily related [parent/child].

Have you tried using the Vue EventBus? A good example: https://alligator.io/vuejs/global-event-bus/

I'm posting the relevant bits here [that I use in couple of my VueJS projects for exactly the same purpose as yours: a click somewhere toggles a CSS class elsewhere :-)]

In your main.js:

const EventBus = new Vue()
Object.defineProperties(Vue.prototype, {
    $bus: {
        get: function () {
          return EventBus
        }
    }
})

The click event in Header.vue would emit an event on the global bus:

this.$bus.$emit('toggle-class-name')

and App.vue would listen for the event and do what's needed:

created () {
    ...
    ...
    this.$bus.$on('toggle-class-name', () => {
        // toggle the class name here
    })
}

Hope this helps!

Upvotes: 1

Related Questions