Nuxt3 优雅地在一个项目中集成 PC 端、移动端多套页面

composables/useDeviceType.ts 判断设备类型

ts 复制代码
import { useRequestEvent } from '#app';

export const useDeviceType = () => {
    const event = useRequestEvent();
    let UA: string
    if (process.client) {
        // 如果是在客户端执行,则通过 navigator 获取 user-agent
        UA = navigator.userAgent
    } else {
        // 如果是在服务端执行,则通过请求头获取 user-agent
        UA = useRequestHeader('user-agent') as string
    }
    const type = ref<'mobile' | 'pc'>('pc');
    const sysType = ref<'ios' | 'android'>('android');

    // 通过 UA 来判断设备类型是 pc 还是 mobile
    const mobileRegex = /Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
    let isMobile = mobileRegex.test(UA);
    if (window?.location?.href.includes('//m') ||
        window?.location?.href.includes('//testm') ||
        (event?.context?.siteConfigNitroOrigin.includes('//m') ||
            event?.context?.siteConfigNitroOrigin.includes('//testm'))
    ) {
        isMobile = true;
    }
    if (isMobile) {
        type.value = 'mobile'
    }

    console.log(type.value, 'type.value useDeviceType')

    const iosRegex = /iPhone|iPod|iPad|iPod/i;
    if (iosRegex.test(UA)) {
        sysType.value = 'ios'
    } else {
        sysType.value = 'android'
    }
    return { type, sysType }
}

app/router.options.ts

ts 复制代码
import type { RouterConfig } from '@nuxt/schema';

// 导出路由配置项
export default <RouterConfig>{
    routes: (_routes) => {
        // 思路是这样的:
        // 如果是移动端访问,则给移动端页面删除路由前缀 /mobile ,给PC端页面添加路由前缀 /pc
        // 如果是 PC 端访问,则给 PC 端页面删除路由前缀 /pc ,给移动端页面添加路由前缀 /mobile

        // 当前设备的类型
        // const targetType: string = (useRuntimeConfig().public.deviceType || 'pc') as string;
        // const targetType: useDeviceType().value;
        const deviceType = useDeviceType();
        if (window?.location?.href.includes('//m') || window?.location?.href.includes('//testm')) {
            deviceType.type.value = 'mobile'
        }
        let targetType = deviceType?.type.value; // 默认为 'pc'
        console.log('window router', window)
        console.log('targetType router', targetType)
        if(!targetType) return [];
        // 不是当前设备类型的另一个类型
        const notTargetType = targetType === 'mobile' ? 'pc' : 'mobile'

        // 找到匹配当前设备的所有页面路由
        let targetRoutes = _routes.filter(item => (item?.name as string)?.startsWith(targetType))
        targetRoutes = targetRoutes.map((item) => {
            // 将路由前缀删除
            item.path = item.path.replace(`/${targetType}`, '') === '' ? '/' : item.path.replace(`/${targetType}`, '')
            // 如果 PC 端、移动端 分别使用的是两套 layout,可以使用下面这段代码去指定布局
            // if (!item.meta?.layout) {
            //   item.meta = {
            //     ...item.meta,
            //     layout: `/${targetType}` === '/mobile' ? '移动端布局名' : 'PC 端布局名',
            //   }
            // }
            return item
        })

        // 找到不匹配当前设备的所有页面路由
        let notTargetRoutes = _routes.filter(item => (item?.name as string)?.startsWith(notTargetType))
        notTargetRoutes = notTargetRoutes.map((item) => {
            // 将路由前缀添加上
            if (!item.path.startsWith(`/${notTargetType}`))
                item.path = `/${notTargetType}${item.path}`
            return item
        })

        console.log('targetRoutes', targetRoutes)
        console.log('notTargetRoutes', notTargetRoutes)

        return [...targetRoutes, ...notTargetRoutes]
    },
}

代码来自: Nuxt3 优雅地在一个项目中集成 PC 端、移动端多套页面

相关推荐
半点寒12W1 小时前
微信小程序实现路由拦截的方法
前端
某公司摸鱼前端2 小时前
uniapp socket 封装 (可拿去直接用)
前端·javascript·websocket·uni-app
要加油哦~2 小时前
vue | 插件 | 移动文件的插件 —— move-file-cli 插件 的安装与使用
前端·javascript·vue.js
小林学习编程2 小时前
Springboot + vue + uni-app小程序web端全套家具商场
前端·vue.js·spring boot
柳鲲鹏2 小时前
WINDOWS最快布署WEB服务器:apache2
服务器·前端·windows
weixin-a153003083163 小时前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
ai小鬼头4 小时前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
一只叫煤球的猫4 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
vvilkim4 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim4 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron