h5页面路由白名单限制
1.判断当前设备是移动端还是pc端,设置对应路由移动端为/m开头,pc为/pc开头
pc:
mobile:
export function getDeviceType() {const userAgent = navigator.userAgent;const isMobile = /Android|iPhone|iPad|iPod|Mobile/i.test(userAgent);return isMobile
}export enum DeviceRoutePath {Mobile = '/m',PC = '/pc'
}
const isMobile = getDeviceType();
const deviceType = isMobile ? DeviceRoutePath.Mobile : DeviceRoutePath.PC;
export { deviceType, isMobile }
2.router.ts
import { createRouter, createWebHistory } from 'vue-router'
import ThirdLogin from './modules/thirdLogin'
import { useLoginStore } from '@/store/modules/login'
import Home from './modules/home'
import { deviceType, isMobile } from '@/utils/router'
import { useRouteConfig } from '@/hooks/useRouteConfig'
import whiteRoute from './modules/whiteRoute'// 设备平台检查守卫
const platformGuard = (to: any, from: any, next: any) => {if (to.meta.platform) {if ((isMobile && to.meta.platform === 'pc') ||(!isMobile && to.meta.platform === 'mobile')) {const redirectPath = to.path.replace(isMobile ? '/pc/' : '/m/',isMobile ? '/m/' : '/pc/')return next(redirectPath)}}return next()
}// 认证守卫
const authGuard = (to: any, from: any, next: any) => {const { token } = useLoginStore().loginData// 增加白名单和免验证路径,根据需求自行调整const { isWhiteListRoute, isBypassPath } = useRouteConfig()if (!token && !isWhiteListRoute(to.name as string) && !isBypassPath(to.path)) {// 将当前要访问的路径作为 redirectUrl 参数const redirectUrl = encodeURIComponent(to.fullPath)return next({path: `${deviceType}/home`,query: { redirectUrl }})}return next()
}const routes = [ThirdLogin,Home,whiteRoute,
]const router = createRouter({history: createWebHistory(),routes: routes
})// 注册全局前置守卫
router.beforeEach(async (to, from, next) => {try {// 按顺序执行守卫const guards = [platformGuard, authGuard]// 创建一个执行守卫的函数const executeGuards = async (index = 0) => {if (index >= guards.length) {return next()}await new Promise((resolve) => {guards[index](to, from, (result: any) => {if (result === undefined) {executeGuards(index + 1).then(resolve)} else {next(result)resolve(null)}})})}await executeGuards()} catch (error) {console.error('路由守卫执行错误:', error)next(false)}
})export default router
3.home.ts
import type { RouteRecordRaw } from 'vue-router'
import { deviceType, isMobile } from '@/utils/router';
import Layout from '@/views/home/pc/layout.vue'export default {path: '/',redirect: (to) => deviceType + '/home',component: isMobile ? '' : Layout,//无router-view 可以不使用children: [{path: '/m/home',component: () => import('@/views/home/mobile/home.vue'),name: 'MobileHome',meta: { name: 'Home', platform: 'mobile' }},{path: '/pc/home',component: () => import('@/views/home/pc/home.vue'),name: 'PCHome',meta: { name: 'Home', platform: 'pc' }}]
} as RouteRecordRaw