I have a ponent which is not to be accessed by non-logged-in user. I implemented this logic into the beforeCreate
hook. Problem is that this doesn't stop the ponent from continuing in loading, which I want it to.
This is my code:
<script>
export default {
beforeCreate: function () {
if (this.$root.auth.user === null) {
this.$router.push({ name: 'auth.login' })
}
},
mounted: function () {
// some code that SHOULD NOT be processed
// if the user isn't authenticated
}
}
</script>
What am I doing wrong?
I have a ponent which is not to be accessed by non-logged-in user. I implemented this logic into the beforeCreate
hook. Problem is that this doesn't stop the ponent from continuing in loading, which I want it to.
This is my code:
<script>
export default {
beforeCreate: function () {
if (this.$root.auth.user === null) {
this.$router.push({ name: 'auth.login' })
}
},
mounted: function () {
// some code that SHOULD NOT be processed
// if the user isn't authenticated
}
}
</script>
What am I doing wrong?
Share asked Sep 18, 2017 at 21:38 Martin HeraleckýMartin Heralecký 5,7893 gold badges31 silver badges67 bronze badges1 Answer
Reset to default 6You should move your beforeCreate function to the router itself. Here's my Auth catch
router.beforeEach(
(to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// if route requires auth and user isn't authenticated
if (!store.state.Authentication.authenticated) {
let query = to.fullPath.match(/^\/$/) ? {} : { redirect: to.fullPath }
next(
{
path: '/login',
query: query
}
)
return
}
}
next()
}
)
It allows me to use my routes definition to handle auth and guest placements.
{
path: '/',
ponent: load('Template'),
children: [
{ path: '', ponent: load('Dashboard'), name: 'Dashboard' }
],
meta: { requiresAuth: true }
},
{
path: '/login',
ponent: load('Authentication/Login'),
name: 'login'
},
By having it in the router it's called before the ponents are initialized by Vue, this will stop processing of any ponent level events.