[web教学] VUE辨认访问设备是pc端还是移动端

[复制链接]
查看961 | 回复0 | 2023-8-23 11:41:36 | 显示全部楼层 |阅读模式 来自 中国北京
一、思绪

有些网站必要区分手机端网页和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文件中配置好差别端口跳转的路由:
  1. export default new Router({
  2.   routes: [
  3.     {
  4.       path: '',
  5.       redirect: '/pc_index'
  6.     },
  7.     {
  8.       path: "/pc_index", // pc端首页
  9.       name: PcIndex,
  10.       component: PcIndex
  11.     },
  12.     {
  13.       path: '/mb_index', // 移动端首页
  14.       name: MbIndex,
  15.       component: MbIndex
  16.     }
  17.   ]
  18. });
复制代码
2,在App.vue中做出判断,并跳转路由即可:
  1. mounted () {
  2.     // 根据不同路由跳转不同页面
  3.     if (this._isMobile()) {
  4.       console.log('手机端')
  5.       this.$router.replace('/mb_index')
  6.     } else {
  7.       console.log('pc端')
  8.       this.$router.replace('/pc_index')
  9.     }
  10.   },
  11.   methods: {
  12.     // 判断是否是手机端,如果是,返回true
  13.     _isMobile () {
  14.       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)
  15.       return flag
  16.     }
  17.   }
复制代码
四、效果 





来源:https://blog.csdn.net/weixin_42966151/article/details/128897332
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则