地址栏并不只是地址栏,跳转传参

100 阅读1分钟

当用户在网站上浏览社交媒体,点击了一个感兴趣的文章链接,却因未登录而被重定向到登录页面,登录后又直接跳转到主页,这并不是良好的用户体验。我们可以通过以下方式改进:

设置路由守卫

在路由设置中,修改 beforeEach 导航守卫,在重定向到登录页面时,将当前页面路径作为查询参数(redirect)传递:

    return localStorage.getItem('token');
}

const protectedRoutes = [
    "Home",
    "About",
    "Product"
];

router.beforeEach((to, from, next) => {
    const isProtected = protectedRoutes.includes(to.name);
    if (isProtected && !isLoggedIn()) {
        next({
            path: '/login',
            query: { redirect: to.fullPath }  // 将当前路径作为重定向参数
        });
    } else {
        next();
    }
});

处理登录过程

在登录页面组件中,登录成功后检查是否存在 redirect 查询参数。如果存在,则将用户重定向回原来的页面;否则,重定向到主页:

    <button @click="login">登录</button>
</template>

<script>
export default {
    methods: {
        login() {
            /* 执行登录逻辑,例如 API 调用 */

            // 模拟成功登录,设置 token
            localStorage.setItem('token', '12345');

            // 检查是否存在重定向参数
            if (this.$route.query.redirect) {
                this.$router.push(this.$route.query.redirect); // 重定向到原始页面
            } else {
                this.$router.push('/'); // 如果没有重定向参数,重定向到主页
            }
        }
    }
}
</script>

解释

  1. 路由守卫 (beforeEach) :

    • 检查是否需要身份验证的路由 (isProtected),以及用户是否未登录 (!isLoggedIn()).
    • 如果条件满足,将用户重定向到登录页面 (/login),并将当前页面的完整路径作为查询参数 (redirect) 传递。
  2. 登录页面:

    • 在成功登录后(通过设置 localStorage 中的 token 模拟),检查是否存在 redirect 查询参数 (this.$route.query.redirect)。
    • 如果存在,将用户重定向回保存的路径 (this.$router.push(this.$route.query.redirect))。
    • 如果不存在,重定向到主页 (this.$router.push('/'))。

通过这样的设置,确保用户在登录后能够回到他们原本想访问的页面,提升了用户体验的流畅度和直观性。