Nuxt.js -- 判断 PC 与 移动端 自动识别跳转

一、 使用 middleware 判断(推荐)

根据浏览器ua判断当前是否为移动设备:
middleware中间件执行流程顺序:

1、nuxt.config.js
2、匹配布局
3、匹配页面

项目根目录下新建 middleware 文件夹,新建 midd.js 文件

export default function ({ isServer, req, redirect, route }) {
  let isMobile = (ua) => {
    return !!ua.match(/AppleWebKit.*Mobile.*/)
  }
  let userAgent = req ? req.headers['user-agent'] : navigator.userAgent || ''
  return isMobile(userAgent) ? redirect('移动端') : ('PC 端')
  // 使用redirect 重定向到外链需要加上前缀:http / https
}

然后在 nuxt.config.js加上对应配置:

router: {
    middleware: ['midd']
},

这样的话在每个页面渲染前都会调用midd.js,如果不需要每个页面都判断的话可以在需要判断跳转的页面里面写,然后把nuxt.config.js里面的去掉。

二、静态文件判断

  • 在 lib 文件夹下新建 isMobile.js (/lib/isMobile.js
;(function() {
  console.log('判断移动端')
  const sUserAgent = navigator.userAgent.toLowerCase()
  if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(sUserAgent)) {
    //跳转移动端页面
    // window.location.replace(``) //跳转后没有后退功能
    console.log('移动端')
  }
})()

nuxt.config.js

module.exports = {
  head: {
    script: [{ src: '/lib/isMobile.js' }],
  }
},
posted @   DL·Coder  阅读(896)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示