VUE识别访问设备是移动端还是pc端

一、思路
有些网站需要区分手机端网页和pc端网页,做到不同设备访问不同的网页,增强用户的使用体验,可以在app.vue中作一个判断(navigator.userAgent),然后跳转不同的路由。

二、原理
navigator.userAgent 属性是一个只读的字符串,声明了浏览器用于 HTTP 请求的用户代理头的值。

例如:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36

然后通过match函数判断是否有包含相应移动端设备名称,从而实现区分两者。

浏览器代号: navigator.appCodeName
浏览器名称: navigator.appName
浏览器版本: navigator.appVersion
启用Cookies: navigator.cookieEnabled
硬件平台: navigator.platform
用户代理: navigator.userAgent
用户代理语言: navigator.language

三、步骤
1,先在router/index.js文件中配置好不同端口跳转的路由:

export default new Router({
  routes: [
    {
      path: '',
      redirect: '/pc_index'
    },
    {
      path: "/pc_index", // pc端首页
      name: PcIndex,
      component: PcIndex
    },
    {
      path: '/mb_index', // 移动端首页
      name: MbIndex,
      component: MbIndex
    }
  ]
});

2,在App.vue中做出判断,并跳转路由即可:

 mounted () {
    // 根据不同路由跳转不同页面
    if (this._isMobile()) {
      console.log('手机端')
      this.$router.replace('/mb_index')
    } else {
      console.log('pc端')
      this.$router.replace('/pc_index')
    }
  },
  methods: {
    // 判断是否是手机端,如果是,返回true
    _isMobile () {
      let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
      return flag
    }
  }

四、结果
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值