[英]How should a user be redirected to another page after successful login in Vue 3
在使用组合 api 的 vue 3 应用程序中,我想根据经过身份验证的用户是否经过验证来做两件事之一。 因此,如果用户未通过验证,请将用户发送到验证页面。 但如果用户已通过验证,请将用户发送到仪表板。
为了实现这一点,我在我的路由器index.js
中使用导航防护,如下所示
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/signin",
name: "signin",
component: () => import("../views/SignIn.vue"),
},
{
path: "/verify",
name: "verify",
component: () => import("../views/Verification.vue"),
meta: { needsAuth: true }
},
{
path: "/dashboard",
name: "dashboard",
component: () => import("../views/UserDashboard.vue"),
meta: { needsAuth: true },
beforeEnter: (to, from, next) => {
if (localStorage.getItem('verified') == "false") next('verify')
}
},
],
});
router.beforeEach(async (to, from, next) => {
if (to.meta.needsAuth && localStorage.getItem('accessToken') == null) next('signin')
else next()
})
export default router
然后在我的 sigin 页面script setup
中,我有以下代码
import { ref } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
const router = useRouter();
const signin = ref({
email: null,
password: null,
});
const loginUser = async () => {
try {
const res = await axios.post(
"https://mydomain/api/login",
signin.value,
{
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
}
);
localStorage.setItem("accessToken", res.data.data.accessToken);
localStorage.setItem("verified", res.data.data.verified);
router.push({ name: "dashboard" });
} catch (error) {
alert(error.response.data.message);
}
};
现在,当我使用未经验证的用户登录时,我会按预期重定向到验证页面。 但是,当我使用经过验证的用户登录时,我永远不会被发送到仪表板,而是应用程序保留在登录视图中。
我似乎无法弄清楚问题是什么。 如何解决此路由问题?
如果用户已通过验证,您是否尝试使用next()
:
beforeEnter: (to, from, next) => {
if (localStorage.getItem('verified') == "false") next('verify')
else next()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.