import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { getToken } from '@/utils/auth'
const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'Index',
component: () => import('@/pages/index.vue') // 注意这里要带上 文件后缀.vue
},
{
path: '/index',
name: 'Index',
component: () => import('@/pages/index.vue') // 注意这里要带上 文件后缀.vue
},
{
path: '/login',
name: 'Login',
component: () => import('@/pages/login.vue') // 注意这里要带上 文件后缀.vue
},
{ name: 'nofound', path: "/:nofound(.*)*", redirect: '/index' }
]
const router = createRouter({
history: createWebHistory(),
routes,
})
// 设置导航守卫 有token 直接进入首页或指定的页面(无法进入登录页面)
router.beforeEach((to, from, next) => {
// 获取token
const TOKEN = getToken()
if (TOKEN) {
if (to.name === 'Login') next('/index')
else next()
} else {
// 没有token 只能访问登录页面 其它页面无法访问
if (to.name === 'Login') next()
else next('/login')
}
})
export default router