vue判断设备是移动端还是pc端
判断pc与手机端,根据不同的设置跳转不同的路由。const routes = [{path: "/",component: () =>import( "../components/test.vue")},{path: "/test", // pc端首页component: () =>import( "../components/test.vue")},{path: '/mi', //
·
欢迎访问我的博客地址 : 博客地址
判断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();
})
更多推荐
已为社区贡献1条内容
所有评论(0)