在router文件中的index.js里存入个本地存储,我根据目标路由的名称进行了条件判断。如果目标路由为首页(即home
),则继续验证用户是否已登录,如果已登录则跳转到关于页(即about
),否则允许访问首页。 对于其他路由,如果用户已登录,则允许访问;如果未登录,则强制跳转到首页。
import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "home",
component: HomeView,
},
{
path: "/about",
name: "about",
component: () => import("../views/AboutView.vue"),
},
];
const router = new VueRouter({
routes,
});
router.beforeEach((to, from, next) => {
const isLoggedIn = sessionStorage.getItem("isLoggedIn");
if (to.name === "home") {
if (isLoggedIn) {
next("/about");
} else {
next();
}
} else {
if (isLoggedIn) {
next();
} else {
next("/");
}
}
});
export default router;
在需要用到路由守卫的登录页面上获取数据,进行判断
login() {
if (this.validate()) {
sessionStorage.setItem("isLoggedIn", true);
this.$router.push("/about");
} else {
this.$alert("账号、密码或者验证码错误,请重新输入", {
confirmButtonText: "确定",
});
this.username = "";
this.password = "";
this.captcha = "";
getList().then((res) => {
this.yzm = res.msg;
});
}
},
validate() {
return (
this.username === "admin" &&
this.password === "123456" &&
this.captcha === this.yzm
);
},