前言:在很多项目中我们需要使用登录功能,在没有登录时无法查看更多内容,但是登录过后点击退出登录,然后返回上一页还可以继续看,这时候就可以用到导航守卫,使在未登录的时候就只能进入到登录页,在前端可以使用 vue 的导航守卫来完成
在此,我使用全局前置守卫 在 router.js 中加入全局前置守卫
//全局前置守卫
router.beforeEach((to, from, next) => {
console.log("beforeEach to:", to);
console.log("beforeEach from", from);
if (to.path != "/" && JSON.parse(sessionStorage.getItem("isLogin")) == false) {
alert("请先登录");
next("/");
}
next();
});
当然别忘了还有这个玩意,否则 router 是无效的
import Router from "vue-router";
const router = new Router({
mode: "history",
routes,
});
这样在登录时候点击登录按钮,给一个判断
//如果账号和密码符合,就缓存一个isLogin为true,也就是已经登录,然后把路由push到应该去的地方
if (this.account == "admin" && this.password == "123456") {
sessionStorage["isLogin"]=true
this.$router.push('./statistics.vue' )
} else {
alert("请输入正确的账号和密码");
}
在点击退出登录时候给一个
//把储存在本地的isLogin改为false,也就是未登录状态,然后把路由push到根目录
sessionStorage.setItem("isLogin",false)
this.$router.push("/")
这个时候退出后再点击返回上一页就会出现

❀❀❀❀❀❀ 完结散花 ❀❀❀❀❀❀
Written ❤️ sywdebug.