vue-判断设备是手机端还是pc端,进行两套页面样式的编写
经常在项目中会有支持 pc 与手机端需求。并且pc与手机端是两个不一样的页面。这时就要求判断设置,根据不同的设置跳转不同的路由。在 router/index.js 中有两个页面。export default new Router({mode: 'history',routes: [{path: '',redirect: '/pc_index'},{path: "/pc_index", // pc端
·
01
经常在项目中会有支持 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;
}
02
首先在App.vue中
<template >
<div id="app" >
<!-- <router-view />-->
<router-view v-if="showPage == 1" name="m" ></router-view>
<router-view v-if="showPage == 2" name="pc" ></router-view>
</div>
</template>
<script>
created中根据_isMobile判断是否手机端,然后路由router-view根据showPage显示,路由会根据name显示移动端和pc端
<script>
export default {
name: 'app',
data () {
return {
showPage: '',
}
},
created () {
if (this._isMobile()) {
this.showPage = 1
} else {
this.showPage = 2
}
console.log(this.showPage)
},
methods: {
_isMobile () {
const 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
},
},
}
</script>
然后定义如下文件夹
接下来看路由如何配置
注意是compinents,不是compinent要加s,此处的default是默认显示的页面,如果pc和m都未定义
{
path: '/home',
components: {
default: () => import('@/views/pc/index'),
pc: () => import('@/views/pc/index'),
m: () => import('@/views/move/index'),
},
},
03正解
01中的要写在router文件夹下的index.js文件里,否则当在项目中用this.$router.resolve来跳转到新页面,也会判断是手机端还是pc端,直接跳转进了首页而进不到想要去的页面。
更多推荐
已为社区贡献5条内容
所有评论(0)