一、思路

有些网站需要区分手机端网页和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
    }
  }

四、结果 

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

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。