Vue object passed through emit not recognized after listened in the other component

Multi tool use
Vue object passed through emit not recognized after listened in the other component
I have two component say componentA and componentB.
In componentA I have a click event that triggers a method that passed the user object as the argument, and this object is then emitted using the event bus. When I successfully listened to the emit in componentB I have assigned the object that was emitted to a variable, I console.log out the variable it showed the object, but when I console.log again the variable outside of the Event.$once the object disappeared.
Any help would be appreciated :)
Thanks!
Here's my code:
componentA
showUserStats(user) {
EventBus.$emit('userInfo', user);
this.$router.push({
name: 'componentB',
params: { id: user._id }
})
}
componentB
created() {
EventBus.$once('userInfo', (user) => {
this.userInfo = user
console.log('userInfo', this.userInfo);
});
console.log('userInfo outside EventBus', this.userInfo);
}
Here is the image of the output
1 Answer
1
This is happening because you're console logging on created
lifecycle event. The console log outside of the $once
call is called immediately on component creation (when the user info isn't assigned) but the console.log inside the $once
is happening only when the event is emitted and in turn the varible / data is assigned.
created
$once
$once
In line with comments: You can't just throw a delay in and expect it to work as it's based on events firing. You've not given us info on when showUserStats
is called so I don't know when this event emits.
showUserStats
With regards to the computed value, that should work as it'll update when the user info is assigned but you'll need to add a check for when it isn't so, something like this:
computed: {
fullName () {
return this.userInfo ? this.userInfo.name + ' ' + this.userInfo.surname : ''
}
}
It'll show blank unless the user info object has been assigned (note: You might need to alter the check based on how you initialise the userInfo
var in data ())
userInfo
computed: { fullName() { return this.userInfo.name + ' ' + this.userInfo.surname; } }
– I-yang Terry Liao
Jul 2 at 13:42
The weird thing is, it works fine when I call the API to retrieve the user info
– I-yang Terry Liao
Jul 2 at 13:45
For what I understand, you're trying to trigger the event each time you click right? If so, then you should be using $on instead of $once
– Luis Mendoza
Jul 2 at 16:41
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thank you for your help, but I have tried giving a delay of 1 second still no luck :( I would like to use the variable in my computed method.
– I-yang Terry Liao
Jul 2 at 13:42