Redirect to requested page after login using vue-router

前端 未结 8 1930
臣服心动
臣服心动 2020-12-07 20:40

In my application some routes are just accessible for authenticated users.
When a unauthenticated user clicks on a link, for which he has to be signed in, he will be redi

相关标签:
8条回答
  • 2020-12-07 21:06

    This will help you @Schwesi .

    Router.beforeEach(
        (to, from, next) => {
            if (to.matched.some(record => record.meta.forVisitors)) {
                if (Vue.auth.isAuthenticated()) {
                    next({
                        path: '/feed'
                    })
                } else
                    next()
            }
            else if (to.matched.some(record => record.meta.forAuth)) {
                if (!Vue.auth.isAuthenticated()) {
                    next({
                        path: '/login'
                    })
                } else
                    next()
            } else
                next()
        }
    );
    
    0 讨论(0)
  • 2020-12-07 21:08

    If route guard is setup as below

    router.beforeEach((to, from, next) => {
        if (to.matched.some(record => record.meta.requiresAuth)) {
            if (!loggedIn) {
                next({
                    path: "/login",
                    query: { redirect: to.fullPath }
                });
            } else {
                next();
            }
        } else {
            next();
        }
    });

    The redirect query can be extracted and used upon successful login

    let searchParams = new URLSearchParams(window.location.search);
    
    if (searchParams.has("redirect")) {
      this.$router.push({ path: `${searchParams.get("redirect")}` });
    } else this.$router.push({ path: "/dashboard" });

    0 讨论(0)
提交回复
热议问题