I want to pass the last route into my router when I'm in /login to redirect the user when is logged to desired route.
So the user go to /payment
I redirect to /login
and when the authentication is ok I want to redirect the user to payement
Here is my router.js :
import ...
Vue.use(Router)
let router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/about',
name: 'about',
component: About
},
{
path: '/payment',
name: 'payment',
component: Payment,
meta: {
requiresAuth: true
}
},
{
path: '/my-account',
name: 'my-account',
component: MyAccount,
meta: {
requiresAuth: true
}
}
]
})
router.beforeEach((to, from, next) => {
console.log('Before Each Routes')
if(to.matched.some(record => record.meta.requiresAuth)) {
if (store.getters.isLoggedIn) {
console.log('Logged in')
next()
return
}
console.log(to.fullPath)
next({
path: '/login',
params: { nextUrl: to.fullPath }
})
return
} else {
console.log(to.fullPath)
next()
}
})
export default router
So I set some console.log and I got this :
if I go directly to /login, Output :
Before Each Routes
/login
Then if I go to /payment, Output :
Before Each Routes
/payment
Before Each Routes
/login
So now when I go in my login component and I use this.$route.params.nextUrl
it's undefined. The next()
parameter doesn't exist and I don't know why.
What I'm doing wrong ?
Use queryParamMap to access query parameters. Another way to access query paramters in Angular is to use queryParamMap property of ActivatedRoute class, which returns an observable with a paramMap object.
If you're using Vue Router you'll push the new URL onto the router in order to do a redirect: this. $router. push('www.yoursite.com/blog') .
beforeEach to listen for routing events globally across the application. This is worth using if you have authentication checks or other pieces of functionality that should be used in every route. Here's an example that simply logs out the route the user is going to and coming from.
It looks like you're confusing two different mechanisms: params and query. Params have to be integral to the url, like /user/:id
while query params are appended automatically.
You want this:
next({
path: '/login',
query: {
nextUrl: to.fullPath,
}
})
Related reading: https://router.vuejs.org/api/#route-object-properties
Tristan's approach above is the best when passing a url as a parameter. However, in normal cases we're passing something like an id so you can use this:
next({ name: 'account', params: { id: 3 } });
Add the replace option to prevent the navigation from appearing in the history:
next({ name: 'account', params: { id: 3 }, replace: true });
I'm using vue-router 3.1.6.
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