记录一下vue的页面登录拦截功能
1.通过设置router 的beforeEach功能实现。
一些点:
-
可以放在main.js中设置,这样可以将最外层的Vue 变成变量,然后通过其获取 vuex的 store数据。
-
router中可以设置 某个页面是否需要登录的meta标识
-
可以使用jquery控制modal窗口。
代码参考:
router.beforeEach((to, from, next) => {
let isLogin = vueApp.$store.state.User.user != null;
//console.log("@登录拦截:", to.path, "==登录状态:", isLogin);
//console.log("页面地址:", to.path, "===", from.path);
//console.log("@参数:", JSON.stringify(to.params));
if (!isLogin && to.matched.some(res => res.meta.loginAuth)) {
next(false) // 取消跳转
//弹出登录框 可以使用jquery
$('#loginDialog').modal('show');
} else {
//通过该方式可以保存 VueRouter 的数据不被刷新
localStorage.setItem('routerParams', JSON.stringify(to.params));
next()
}
});