vue识别设备类型并跳转路由

626 阅读1分钟

如果你的网站不是响应式布局(即根据窗口大小调整布局),或者你的网站针对PC端和手机、平板端有不同的网站。这时候就要增加一个判断,根据设备类型来分发路由。

首先你需要一个函数,用来从 UserAgent 里读取设备类型并判断

async function getTerminalType(){
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        return  'mobile';
    } else if (/(Android)/i.test(navigator.userAgent)) {
        return  'mobile';
    } else {
        return 'pc';
    }
}

这里,我把苹果系的设备标记为 mobile,安卓系的也标记为 mobile,其余的设备标记为pc,如有特定需求,再区分苹果和安卓。

那么相应的,你会根据这两类设备配置两个不同的路由。

const routes = [
    {
        path: '/',
        name: 'root',
        redirect: '/pc/'  // 默认是pc端
    },
    {
        path: '/pc',
        name: 'pc',
        component: () => import('../views/pc/index'),
        children: [
        	...
        ],
    },
    {
        path: '/mobile',
        name: 'mobile',
        component: () => import('../views/mobile/index'),
        children: [
        	...
        ],
    }
]

如何在每次路由跳转时都进行判断?我们可以使用路由守卫实现

const router = createRouter({
    history: createWebHashHistory(),
    routes // 上个代码框里写了
})

router.beforeEach(async (to, from, next)=>{
    let terminalType = await getTerminalType();
    if (terminalType === 'mobile' && to.fullPath.indexOf('/pc')!==-1) {
        await next({path: '/mobile'})
    } else if (terminalType === 'pc' && to.fullPath.indexOf('/mobile')!==-1) {
        await next({path: '/pc'})
    } else {
        await next()
    }
});

这样就大功告成了。