pc 移动端 双端切换-路由判断
该封装主要以分类形式,实现对路由的简易区分。便于项目管理。
创建好项目,勾选路由插件,会自动生成 router文件夹与index.ts 。
/* * @description: pc端 路由 * @Author: Jay * @Date: 2022-06-13 10:45:21 * @LastEditors: Jay * @LastEditTime: 2022-06-13 11:54:00 */ import { RouteRecordRaw } from 'vue-router' export const pcRouter: Array<RouteRecordRaw> = [ { path: '/p-Home', name: 'pHome', component: () => import("../views/pc/pc-home/pc-home.vue"), meta: { //路由为pc端 type: 'pc', //页面标题 title: "pc首页" } }, { path: '/p-Login', name: 'pLogin', component: () => import("../views/pc/pc-login/pc-login.vue"), meta: { type: 'pc', title: "登录" } }, ]
/* * @description: 移动端路由 * @Author: Jay * @Date: 2022-06-13 10:45:38 * @LastEditors: Jay * @LastEditTime: 2022-06-13 14:18:20 */ import { RouteRecordRaw } from 'vue-router' export const mobileRouter: Array<RouteRecordRaw> = [ { path: '/m-Home', name: 'mHome', component: () => import('../views/moblie/m-home/m-home.vue'), meta: { //路由为移动端 type: 'mobile', //页面标题 title: "移动端首页" } }, { path: '/m-login', name: 'mLogin', component: () => import('../views/moblie/m-login/m-login.vue'), meta: { type: 'mobile', title: "登录" } } ]
/* * @description: 路由 * @Author: Jay * @Date: 2022-06-13 10:27:19 * @LastEditors: Jay * @LastEditTime: 2022-06-13 13:49:48 */ import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' // 导入 移动 pc 路由 import { mobileRouter } from "./mobile-index"; import { pcRouter } from "./pc-index"; //判断设备 const Device = /phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone/i; const redirectPath: string = Device.test(navigator.userAgent) ? "/m-home" : "/p-home"; const routes: Array<RouteRecordRaw> = [ // 跟目录 { path: "/", redirect: redirectPath, } ] const router = createRouter({ history: createWebHistory(process.env.BASE_URL), //整合路由 routes: [...routes, ...mobileRouter, ...pcRouter], }) /* 前置 路由守卫 */ router.beforeEach((to, from, next) => { // 当移动端试图访问pc端界面时 if (Device.test(navigator.userAgent) && to.meta.type !== "mobile") { const routers = router.options.routes.filter((v) => v.name?.toString().startsWith("m")); const path = routers?.filter((v) => v.name?.toString().split("-")[1] === to.name?.toString().split("-")[1] )[0]; if (path) { next(path.path); } else { next("/"); } } // 当pc端页面试图访问移动端页面时 if (!Device.test(navigator.userAgent) && to.meta.type !== "pc") { const routers = router.options.routes; const path = routers.filter((v) => v.name?.toString().split("-")[1] === to.name?.toString().split("-")[1] )[0].path; if (path) { next(path); } else { next("/"); } } next(); }) /* 后置 路由守卫 */ router.afterEach((to: any, from) => { //更改每个页面的标题 document.title = to.meta.title; }) export default router
本文来自博客园,作者:虚乄,转载请注明原文链接:https://www.cnblogs.com/lovejielive/p/16371610.html