问题记录
项目使用element开发,需要根据移动端还是PC端进入不同的主页。
// router/index.js
export default new Router({
mode: 'history',
routes: [
{
path: "/",
name: "layout",
redirect: "/pc_index",
component: () => import("./views/Layout.vue"),
children: [
{
path: "/m_index", //移动端
name: "mIndex",
component: () => import("./views/m_index.vue")
},
{
path: "/pc_index", //pc端
name: "pcIndex",
component: () => import("./views/pc_index.vue")
},
}
]
})
百度了一圈,几乎都是下面这个方法:
//在 App.vue 里添加
methods: {
// 添加判断方法
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;
}
},
mounted: {
if(this.isMobile) {
alert("移动端");
this.$router.replace('/pc_index');
}else {
alert("pc端");
this.$router.replace('/m_index');
}
}
但这个会导致一个问题,除了Header的跳转链接,其他跳转链接都跳转到主页了
解决方法
在 router/index.js 里使用router.beforeEach,如果是跳转到pc_index的,就判断是不是移动端
//在 router/index.js 增加
router.beforeEach((to, from, next) => {
if (to.path == '/pc_index') {
if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
router.push({ path: '/m_index', });
}
}
next();
});