1

I am trying to use a global eventbus in VueJs but have been unsuccessful so far.

I have the following code. When I navigate from ResetPassword to Login screen, I should see the successMessage with a Your password has been changed successfully. Please login to continue but it always shows a blank.

What could I be doing wrong?

plugins.js:

Vue.prototype.$eventHub = new Vue();

ChangePassword.vue:

methods: 
  {  
    ChangePassword() 
    {
      this.$eventHub.$emit('navigation-message', 'Your password has been changed successfully. Please login to continue.');
      this.$router.push({ name: 'login'});                  
    },
  },

Login.vue:

data() {
    return {
      successMessage:'',
    };
  },
    created () 
      {
        this.$eventHub.$once('navigation-message', this.successMessage);
      },
      beforeDestroy() 
      {
        this.$eventHub.$off('navigation-message');
      },

Update: 12/8/2019: I changed the login.vue as per comment by @tony19 but the issue still exists.

Login.vue:

created () 
  {
    this.$eventHub.$once('navigation-message', (payload)=>
    {
      updateSuccessMessage(payload);    
    });
  },
methods: 
  { 
    updateSuccessMessage(payload) 
    {
      this.successMessage=payload;
    },
Ajit Goel
  • 4,180
  • 7
  • 59
  • 107
  • `this.$eventHub.$once('navigation-message', this.successMessage);` doesn't look right. The second parameter should be a function, but you've set it to `successMessage`, which is a string. – tony19 Dec 08 '19 at 07:34
  • @tony19, i made the change but the issue still exists. – Ajit Goel Dec 08 '19 at 14:03
  • Does the `Login` page exist when you fire the event? If your change-password view is separate from the login view, it probably won't be created until you push the route, at which point the event listener setup is too late. I'm guessing that's what is happening. – tony19 Dec 08 '19 at 20:53
  • Thank you @tony19 fir your input. I got the same input on the vuejs forums. https://forum.vuejs.org/t/global-eventbus-not-working/81641 – Ajit Goel Dec 09 '19 at 01:18

1 Answers1

0

You need to add this.

created () {
  this.$eventHub.$on('navigation-message', payload => {
    this.updateSuccessMessage(payload) 
  })
},
methods: {
  updateSuccessMessage(payload) {
    this.successMessage = payload
  }
}

Also make sure you're actually importing plugin.js globally (e.g. inside your main file where you import Vue) and make sure your components have access to it.

Try this:

created() {
  console.log(this.$eventHub)
}
AlekseyHoffman
  • 2,438
  • 1
  • 8
  • 31