I’m using an EventBus in my code so I can manage how my navbar changes depending on the user that has logged in, if he’s admin the navbar will have more functions.
The fact is that when I log in, the login component emits something with an $emit, this event is recieved by another component, which is the navbar.
That works fine, if he’s logged in and he’s an admin, he’ll have more things to interact with in the navbar, but when I refresh the page is like the events desappear and the navbar works like there’s no one even logged in.
Thank you so much in advance!!!
Login.vue
I call these methods when an user logs in and is also an admin.
emitMethod () {
EventBus.$emit(‘logged-in’, ‘loggedin’)
},
adminMethod () {
EventBus.$emit(‘isadmin’, ‘isadmin’)
}
Navbar.vue
The navbar option ‘Users’
<li v-if=”auth==’loggedin’ && admin==’isadmin’” class=”nav-item”>
<router-link class=”nav-link” to=”/users”>Users</router-link>
</li>
This is the method login() that emits the event
login () {
axios.post(‘signin’, {
email: this.email,
password: this.password
}).then(res => {
localStorage.setItem(‘usertoken’, res.data.token)
const token = localStorage.usertoken
const decoded = jwtDecode(token)
this.admin = decoded.sub.isAdmin
console.log(‘Es admin? ‘ + this.admin)
this.email = ‘’
this.password = ‘’
//alert(‘Logueado correctamente’)
this.emitMethod()
if (this.admin === true) {
this.adminMethod()
}
router.push({ name: ‘Profile’ })
}).catch(err => {
this.password = ‘’
alert(‘Usuario o contrasea incorrectos’)
console.log(err)
})
},
emitMethod () {
EventBus.$emit(‘logged-in’, ‘loggedin’)
},
adminMethod () {
EventBus.$emit(‘isadmin’, ‘isadmin’)
}
}
And this the script section of the component Navbar.vue
export default {
data () {
return {
auth: ‘’,
user: ‘’,
admin: ‘’,
users: ‘’
}
},
methods: {
logout () {
localStorage.removeItem(‘usertoken’)
}
},
mounted () {
EventBus.$on(‘logged-in’, status => {
this.auth = status
})
EventBus.$on(‘isadmin’, status => {
this.admin = status
})
}
}
Solution :
When you refresh the page, all components will be reset and will start from the initial state again. You need to either detect that the user is logged-in in Login.vue.js initialization and emit the event OR pass some prop to the Navbar component that would inform is the user is logged in.
Solution 2:
Consider that you logged in and redirected to home admin page. In the code you write the function that only fire event in Login.vue.js guess on click login button. But after login process and redirecting to admin homepage when you refresh the page there is no $emit event (EventBus.$emit(‘logged-in’, ‘loggedin’)) in current page. And that is why the Navbar can not get if somebody is logged in or not.
You must check if user logged in every time when you refresh page and $emit logged-in event after this check. Then the program will work as you want