vue使用redired对路由重定向:
{
path: '*',
redirect: {
name: 'login'
}
}
设置根目录
{
path: "/",
name: 'login',
component: login,
}
设置地址栏地址正常显示:添加mode: 'history',
设置页面是否登录,登录后正常跳转,未登录跳转至指定页(登录页)
在需要过滤的页面添加mate>auth,不需要过滤页面不用添加。
export default new Router({
mode: 'history',
routes: [{
path: "/",
name: 'login',
component: login,
}, {
path: '/HelloWorld',
name: 'HelloWorld',
component: HelloWorld,
meta: {
auth: true
}]
})
在main.js中添加router.beforeach守卫
router.beforeEach((to, from, next) => {
if (to.matched.some(m => m.meta.auth)) {
// 对路由进行验证
var token=sessionStorage.getItem("token");
if (token) { // 已经登陆
next() // 正常跳转到你设置好的页面
} else {
// 未登录则跳转到登陆界面,query:{ Rurl: to.fullPath}表示把当前路由信息传递过去方便登录后跳转回来;
next({
name: 'login',
query: {
Rurl: to.fullPath
}
})
}
} else {
next()
}
})
可以在登录的时候存入session,在访问页面进行验证。记得设置next(),