在router.js下写入
// 路由守卫
router.beforeEach((to, from, next) => {
// to要跳转到的路径
// from从哪个路径来
// next往下执行的回调
// 在localStorage中获取token
let token = localStorage.getItem('username')
// 判断该页面是否需要登录
if (to.meta.auth) {
// 如果token存在直接跳转
if (token) {
if (to.path === '/login') {
next('/pingTaiGL/keHuDuan')
} else {
next()
}
} else {
if (to.path === '/login') {
next()
} else {
next('/login')
}
}
} else {
// 如果不需要登录,则直接跳转到对应页面
next()
}
})
路由
{
path: '/yongHuGL',
component: () => import('../views/yongHuGL/index.vue'),
meta: {
title: '用户管理',
auth:true//添加字段判断该页面是否需要登录
},
},
{
path: '/pingTaiGL/keHuDuan',
component: () => import('../views/pingTaiGL/keHuDuan/index.vue'),
meta: {
title: '客户端',
auth:true//添加字段判断该页面是否需要登录
},
},
{
path: '/pingTaiGL/shiPeiQi',
component: () => import('../views/pingTaiGL/shiPeiQi/index.vue'),
meta: {
title: '适配器',
auth:true//添加字段判断该页面是否需要登录
},
},
登录
async onSubmit() {
try {
const result = await this.$refs.form.validate()
if (!result) return
localStorage.setItem('username', this.formData.username) //存储
if (this.$route.query.redirect) {
this.$router.push({ path: this.$route.query.redirect })
// 如不存在,直接跳转到首页
} else {
this.$router.push({ path: '/pingTaiGL/keHuDuan' })
window.location.reload()
}
} catch (e) {
// ignore validate error
if (e === false) return
throw e
}
},