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 @ 2023-03-17 16:57  DL·Coder  阅读(695)  评论(0编辑  收藏  举报