vue-判断设备是手机端还是pc端

时间:2023-01-25 02:49:13

  经常在项目中会有支持 pc 与手机端需求。并且pc与手机端是两个不一样的页面。这时就要求判断设置,根据不同的设置跳转不同的路由。

【代码演示】

  在 router/index.js 中有两个页面。

export default new Router({
mode: 'history',
routes: [
{
path: '',
redirect: '/pc_index'
},
{
path: "/pc_index", // pc端首页
name: PcIndex,
component: PcIndex
},
{
path: '/m_index', // 手机端首页
name: MIndex,
component: MIndex
}
]
})

  在 App.vue 的 mounted 方法中对设置进行判断,如下:

  mounted() {
if (this._isMobile()) {
alert("手机端");
this.$router.replace('/m_index');
} else {
alert("pc端");
this.$router.replace('/pc_index');
}
}

  其中  _isMobile() 方法如下:

  _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;
}

【效果展示】

  chrome 浏览器中 pc 模式下刷新,显示如下:

  vue-判断设备是手机端还是pc端

  chrom 浏览器中 mobile 模式下刷新,显示如下:

  vue-判断设备是手机端还是pc端

  用手机真机测试也如预期弹出了 手机端 弹框。