VUE判断是移动端还是PC端进入对应的主页

问题记录

项目使用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();
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值