欢迎访问我的博客地址 : 博客地址

判断pc与手机端,根据不同的设置跳转不同的路由。

const routes = [
  {
    path: "",
    redirect:'/test'
  },
  {
    path: "/test", // pc端首页
    component: () =>
        import( "../components/test.vue")
    },
  {
    path: '/mi', // 手机端首页
    component: () =>
        import( "../components/mi.vue")
    }
];

const router = new VueRouter({
  routes
});

export default router;

在 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('/mi');
    } else {
      alert("pc端");
      this.$router.replace('/test');
    }
  }

在这里插入图片描述
在这里插入图片描述
但这个会导致一个问题,除了Header的跳转链接,其他跳转链接都跳转到主页了
解决方法
在 router/index.js 里使用router.beforeEach,如果是跳转到pc_index的,就判断是不是移动端

//在 router/index.js 增加
router.beforeEach((to, from, next) => {
//NProgress.start();
const auth = ['/login'];
if (!auth.includes(to.fullPath)) {
  const token = sessionStorage.getItem('token');
  if (!token) {
    next('/login');
  } else {
    next();
  }
} else {
  next();
}
})
 router.afterEach(() => {
//   NProgress.done();
 })
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐