vue vue-router实现路由拦截功能
vue vue-router实现路由拦截功能1、目录结构2、设置路由拦截、路由配置如下,在这里自定义了一个对象的参数meta: {authRequired: true}来标记哪些路由是需要登录验证的,导航被触发的时候只要判断是否目标路由中是否有meta这个对象,且meta包含authRequired属性,其值为true。这里访问带有meta对象的路由是被拦截的。{path: '/config',n
·
vue vue-router实现路由拦截功能
1、目录结构
2、设置路由拦截、
路由配置如下,在这里自定义了一个对象的参数meta: {authRequired: true}来标记哪些路由是需要登录验证的,导航被触发的时候只要判断是否目标路由中是否有meta这个对象,且meta包含authRequired属性,其值为true。这里访问带有meta对象的路由是被拦截的。
{
path: '/config',
name: 'config',
meta: {
requireAuth: true
},
component: Config
},
{
path: '/about1',
name: 'about1',
meta: {
requireAuth: true
},
component: About1
},
{
path: '/app',
name: 'app',
component: App
},
{
path: '/application',
name: 'application',
meta: {
requireAuth: true
},
component: Application
},
3、全局函数beforeEach
main.js通过router.beforeEach全局函数,每次路由跳转都会出发函数判断是否有登录信息
router.beforeEach((to, from, next) => {
if (to.matched.some(res => res.meta.requireAuth)) { // 验证是否需要登陆
var id=window.sessionStorage.getItem('userId');
console.log(id)
if (id) { // 查询本地存储信息是否已经登陆
next();
} else {
next({
path: '/login', // 未登录则跳转至login页面
redirect: '/main2' // 登陆成功后回到当前页面,这里传值给login页面,to.fullPath为当前点击的页面
});
}
} else {
next();
}
}
4、在登陆界面利用sessionStorage将信息存入到全局变量
login() {
axios.get('http://192.168.56.1:8081/sel/1', {// /gr/goods/add
userid: this.loginForm.userid,
pwd: this.loginForm.pwd,
}).then((res) => {
console.log(res);
console.log(res.data.msg);
this.$store.commit('setUserId',this.loginForm.userid);
this.$store.commit('setUserPwd',this.loginForm.pwd);
console.log(this.loginForm.userid);
console.log(this.loginForm.userpwd);
console.log("打印的id为:"+sessionStorage.getItem('userId'));
console.log("打印的pwd为:"+sessionStorage.getItem('userPwd'));
注意:
之后每次进行路由的时候都会判断登录信息,在注销的时候调用函数,;利用sessionStroage.clear()将全局信息清楚。防止注销之后路由拦截失效
更多推荐
已为社区贡献1条内容
所有评论(0)