天天看點

關于vue.js實作PC端與APP切換渲染同路由

關于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;  
           

最後祝大家,牛年大吉,心想事成!

繼續閱讀