关于vue.js实现PC端与APP切换渲染同路由
-
- main.js
- APP.vue
- index.js
关于pc端和app切换网上很多教程是使用的在入库文件"APP.vue"添加判断,这确实很方便,但是也会延伸出很多BUG,比如刷新页面会再一次进入入口文件,路由又会重新刷新到入口文件定义的地址,于是想到使用路由守卫来判断是pc端还是mobile端。
路由守卫地址:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
main.js
//定义移动端
function _isMobile() {
let flag = navigator.userAgent.match(/(phone|pad|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows phone)/i
);
return flag;
}
// 路由守卫
router.beforeEach((to, from, next) => {
// 初始化路径,对引路由index.js,如果没设置可以设置一个路径为'/'的路由
if (to.path == "/") { //重点,如果没有写这个判断,会导致死循环栈溢出
if (_isMobile()) {
// 手机端
next("/mobile/home");
} else {
// pc端
next("/pc/home");
}
} else {
if (_isMobile()) {
// 切换手机端时判断路径前缀是否是'mobile',如果不是用replace替换成'mobile'
let path = to.path.replace(/pc/g, "mobile");
to.path.indexOf("mobile") != -1 ? next() : next(path);
} else {
// pc端同理
let path = to.path.replace(/mobile/g, "pc");
to.path.indexOf("pc") != -1 ? next() : next(path);
}
}
});
APP.vue
app.vue主要是控制pc端和移动端组件的显隐
<template>
<div id="app">
<div class="mobileTop" v-if="this.deviceType ==='mobile'">
<Top class="thisTop"></Top>
</div>
<div class="pcTop" v-if="this.deviceType ==='pc'">
<TopPc></TopPc>
</div>
<router-view />
</div>
</template>
data(){
return {
deviceType:'',
}
},
mounted(){
if (this._isMobile()) {
// 手机端
this.deviceType = 'mobile'
} else {
// pc端
this.deviceType = 'pc'
}
},
methods:{
_isMobile() {
let flag = navigator.userAgent.match(
/(phone|pad|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows phone)/i
);
return flag;
},
}
index.js
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "which",
component: () => import("@/views/which"),
},
// pc端
{
path: '/pc/home',
name: 'pc/home',
component: ()=>import("@/views/pc/home"),
},
// 手机端
{
path: '/mobile/home',
name: 'mobile/homepage',
component: ()=>import("@/views/mobile/index.vue"),
}
{ path: "/404", component: () => import("@/views/404") },
{ path: "*", redirect: "/404" }
];
const router = new VueRouter({
// mode: "history",
// base: process.env.BASE_URL,
routes
});
export default router;
最后祝大家,牛年大吉,心想事成!