3

I am creating a small client-side Vuejs application and have a bit of trouble with assigning data to a variable. In a login component I am emitting user data with an eventBus, and in an index component I receive the data from the eventbus within the mounted: function (). I have no trouble with receiving the data, but what I would like to do is assign this received data to the currentUser variable. This is what I have in the index component:

mounted: function () {
    eventBus.$on('thisEvent', function (userObject) {
        console.log('event received!', userObject)
        this.currentUser = userObject.user
        console.log('The user: ', this.currentUser) // Shows correct new user data
    }.bind(this))
    console.log('User outside eventbus:', this.currentUser) // Shows empty user
}

And this is how the user looks like in the data:

data: function () {
  return {
     currentUser: {
     firstname: '',
     lastname: '',
     last_login: ''
    }
  }
}

I cannot figure out why the currentUser is emptied outside the eventbus. Thanks in advance!

**Edit: ** This is how I have it now in my index.vue

**Edit 2: ** This shows the output of the console logs. The left one shows the user object in the eventBus, the right one shows the console.log(this) outside the eventBus, with empty currentUser object

This is the $emit of the eventBus, this is being called when the get request response is successfull. The code is in the login.vue, where an authenticated user object gets filled, and transfers this data to the index.vue.

eventBus.$emit('thisEvent', { user: this.user })

11
  • The code in question should work fine, the problem seems to be somewhere else. Can you post the whole code on jsfiddle? Commented Mar 1, 2017 at 11:51
  • @AmreshVenugopal I have edited the post and added a screenshot, hope this makes it more clear! Commented Mar 1, 2017 at 12:19
  • Could you please add the console screenshots as well? Commented Mar 1, 2017 at 12:22
  • @AmreshVenugopal added the other screenshot! Commented Mar 1, 2017 at 12:27
  • So the first console.log(this) (inside the eventBus.on) didnt print anything ? Commented Mar 1, 2017 at 12:30

2 Answers 2

1

Using an arrow function would help you as it doesn't bind its own context.

mounted: function () {
  eventBus.$on('thisEvent', (userObject) => {
    console.log('event received!', userObject)
    this.currentUser = userObject.user
    console.log('The user: ', this.currentUser)
  })
  console.log('User outside eventbus:', this.currentUser)
}

another way: (If you're not using babel or want to support browsers without ES6 support)

mounted: function () {
  var self = this
  eventBus.$on('thisEvent', function (userObject) {
    console.log('event received!', userObject)
    self.currentUser = userObject.user
    console.log('The user: ', self.currentUser)
  })
  console.log('User outside eventbus:', self.currentUser)
}

EDIT

The code in the question and the solutions posted in the thread work just fine. The output that you see is perfectly normal.

mounted: function () {
  eventBus.$on('thisEvent', function (userObject) {
    console.log('event received!', userObject)
    this.currentUser = userObject.user
    console.log('The user: ', this.currentUser) // Shows correct new user data
  }.bind(this))
  console.log('User outside eventbus:', this.currentUser) // Shows empty user
}

The mounted lifecycle hook is called when the component's template and data is ready and rendered.

(You could do the same thing in the created hook as what you have done in mounted)

So

console.log('User outside eventbus:', this.currentUser)

gets logged before your eventBus emits an event.

you can easily check this using a watch like so:

watch: {
  currentUser(newValue, oldValue) {
    console.log(newValue, oldValue)
  }
}

Here is a working jsfiddle

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

14 Comments

Well there are no need for self since you are using let keyoword which also part of ECMAScript 6 specifications, as arrows functions are as well ;)
I'll remove let I just want to add the list of ways in which this can be done :) thanks.
Yeah, your answer is totally good, I just wanted to point out that - If OP doesn't use Babel but wants to support older browsers.
@BelminBedak I'll add that above that part of answer.
Thanks for your reply, I have tried your solution but somehow the user is still empty..
|
0

I cannot figure out why the currentUser is emptied outside the eventbus.

Because of the this scope. Inside classic function syntax you are binding this from function. Use arrow function shown below and it will work as it does not bind this so this.currentUser will update your component data, not just function data.

mounted: function () {
    eventBus.$on('thisEvent', (userObject) => {
        console.log('event received!', userObject)
        this.currentUser = userObject.user
        console.log('The user: ', this.currentUser) // Shows correct new user data
    })
    console.log('User outside eventbus:', this.currentUser) // Shows empty user
}

If above somehow not working, try this solution:

mounted: function () {
        let _self = this;
        eventBus.$on('thisEvent', (userObject) => {
            console.log('event received!', userObject)
            _self.currentUser = userObject.user
            console.log('The user: ', _self.currentUser) // Shows correct new user data
        })
        console.log('User outside eventbus:', _self.currentUser) // Shows empty user
    }

7 Comments

Remove the bind
Thank you for your reply, I have also tried your solution but somehow the user is still empty..
@EleinaNieborg you could try with the storing vue instance into the variable, something like this var vm = new Vue({// other code...}), and then you can acess user by typing vm.currentUser - that should be pointet to correct context
Eleina it is really impossible. Please try to show us your code by JSFiddle or Webpack bin. Did you remove bind(this) ?
Please look for typos etc. This code should work straight forward
|

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.