首页IT科技VUE访问某个页面(VUE识别访问设备是pc端还是移动端)

VUE访问某个页面(VUE识别访问设备是pc端还是移动端)

时间2025-08-05 04:34:01分类IT科技浏览4692
导读:一、思路 有些网站需要区分手机端网页和pc端网页,做到不同设备访问不同的网页,增强用户的使用体验,可以在app.vue中作一个判断(...

一             、思路

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

四             、结果 

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
echarts横纵坐标设置(echarts 横纵坐标设置)