I'm new in VueJS, I'm using VueJS 2 Webpack template. I was trying to redirect from login component to home component if login successful, I've tried many things but I still getting errors. Here is my routing:
const router = new VueRouter({
mode: 'history',
routes: [{
'name': 'home',
path: '/',
component: require('./components/Home.vue'),
beforeEnter: (to, from, next) => {
if (!localStorage.getItem('user')) {
next('/login')
}
}
}, {
'name': 'profile',
path: '/profile',
component: require('./components/Profile.vue'),
beforeEnter: (to, from, next) => {
if (!localStorage.getItem('user')) {
next('/login')
}
}
}, {
'name': 'login',
path: '/login',
component: require('./components/Login.vue')
}, {
'name': 'new',
path: '/new',
component: require('./components/New.vue'),
beforeEnter: (to, from, next) => {
if (!localStorage.getItem('user')) {
next('/login')
}
}
}, {
'name': 'signup',
path: '/signup',
component: require('./components/Signup.vue')
}, {
'name': 'logout',
path: '/logout',
beforeEnter: (to, from, next) => {
localStorage.removeItem('user')
next('/login')
}
}, {
'name': 'article',
path: '/article/:id',
component: require('./components/Article.vue'),
beforeEnter: (to, from, next) => {
if (!localStorage.getItem('user')) {
next('/login')
}
}
}]
})
And that's what I tried to get redirected to home component:
this.$router.replace(this.$router.go('/'))
And I got this error:
Uncaught (in promise) TypeError: Cannot read property 'name' of undefined(…)
this.$router.replace()
expects a location.
this.$router.go('/')
travels through the browser history so it shouldn't actually return anything. It's essentially like window.history.go(Number)
.
You likely want to do this.$router.replace('/')
if you want to replace the page you're on.
Also. I'd check out this part of the documentation. You can put a lot of your repetitive code in a beforeEach
.
https://router.vuejs.org/en/advanced/meta.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With