0

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?

1
  • Be more specific, what do you wanna achieve and what error do you get? Commented Sep 27, 2018 at 6:33

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you gvk! :) Your explanation helped me to found the solution. You save my day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.