最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript實現(xiàn)pc端和移動端頁面切換的兩種基本方案

 更新時間:2025年06月22日 08:44:27   作者:拉不動的豬  
這篇文章主要為大家詳細介紹了JavaScript實現(xiàn)pc端和移動端頁面切換的兩種方法,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下

一、完整目錄結構

src/
├── router/
│   ├── index.js           # 主路由配置
│   ├── mobileRoutes.js    # 移動端路由
│   └── pcRoutes.js        # PC端路由
├── views/
│   ├── mobile/            # 移動端視圖
│   │   ├── Home.vue
│   │   ├── Product.vue
│   │   └── Cart.vue
│   └── pc/                # PC端視圖
│       ├── Home.vue
│       ├── Product.vue
│       └── Cart.vue
├── utils/
│   ├── device.js          # 設備檢測工具
│   └── storage.js         # 本地存儲工具
├── App.vue
└── main.js                # 入口文件

二、核心文件實現(xiàn)

1. 設備檢測工具(utils/device.js)

// 檢測設備類型
export function detectDevice() {
  // 方案1: 通過User-Agent檢測
  const userAgent = navigator.userAgent.toLowerCase();
  const isMobile = /mobile|android|iphone|ipad|phone/i.test(userAgent);
  
  // 方案2: 通過屏幕尺寸檢測(處理平板等特殊情況)
  const isSmallScreen = window.innerWidth < 768;
  
  return isMobile || isSmallScreen ? 'mobile' : 'pc';
}

// 監(jiān)聽屏幕變化
export function setupDeviceWatcher(callback) {
  const updateDevice = () => {
    const device = detectDevice();
    callback(device);
  };

  window.addEventListener('resize', updateDevice);
  updateDevice(); // 初始化檢測

  // 返回清理函數(shù)
  return () => window.removeEventListener('resize', updateDevice);
}

2. 移動端路由(router/mobileRoutes.js)

export const mobileRoutes = [
  {
    path: '/',
    name: 'MobileHome',
    component: () => import('@/views/mobile/Home.vue'),
    meta: { device: 'mobile' }
  },
  {
    path: '/product/:id',
    name: 'MobileProduct',
    component: () => import('@/views/mobile/Product.vue'),
    meta: { device: 'mobile' }
  },
  {
    path: '/cart',
    name: 'MobileCart',
    component: () => import('@/views/mobile/Cart.vue'),
    meta: { device: 'mobile', requiresAuth: true }
  },
  {
    path: '/login',
    name: 'MobileLogin',
    component: () => import('@/views/mobile/Login.vue'),
    meta: { device: 'mobile' }
  }
];

3. PC 端路由(router/pcRoutes.js)

export const pcRoutes = [
  {
    path: '/',
    name: 'PcHome',
    component: () => import('@/views/pc/Home.vue'),
    meta: { device: 'pc' }
  },
  {
    path: '/product/:id',
    name: 'PcProduct',
    component: () => import('@/views/pc/Product.vue'),
    meta: { device: 'pc' }
  },
  {
    path: '/cart',
    name: 'PcCart',
    component: () => import('@/views/pc/Cart.vue'),
    meta: { device: 'pc', requiresAuth: true }
  },
  {
    path: '/login',
    name: 'PcLogin',
    component: () => import('@/views/pc/Login.vue'),
    meta: { device: 'pc' }
  }
];

4. 主路由配置(router/index.js)

import { createRouter, createWebHistory } from 'vue-router';
import { mobileRoutes } from './mobileRoutes';
import { pcRoutes } from './pcRoutes';
import { detectDevice } from '@/utils/device';

// 創(chuàng)建基礎路由(公共路由)
const commonRoutes = [
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes: commonRoutes // 初始只包含公共路由
});

// 初始化路由
export function initRouter() {
  const device = detectDevice();
  const routes = device === 'mobile' ? mobileRoutes : pcRoutes;
  
  // 清空現(xiàn)有路由(保留commonRoutes)
  router.matcher = createRouter({
    history: createWebHistory(),
    routes: commonRoutes
  }).matcher;
  
  // 添加設備專屬路由
  routes.forEach(route => {
    router.addRoute(route);
  });
  
  return device;
}

// 路由守衛(wèi):防止設備與路由不匹配
router.beforeEach((to, from, next) => {
  const currentDevice = detectDevice();
  
  // 檢查目標路由是否存在且匹配當前設備
  const isRouteExists = router.getRoutes().some(
    route => route.name === to.name
  );
  
  if (!isRouteExists) {
    // 路由不存在,重定向到對應設備的首頁
    const homeRoute = currentDevice === 'mobile' 
      ? { name: 'MobileHome' } 
      : { name: 'PcHome' };
    next(homeRoute);
  } else {
    next();
  }
});

export default router;

5. 入口文件(main.js)

import { createApp } from 'vue';
import App from './App.vue';
import router, { initRouter } from './router';
import { setupDeviceWatcher } from './utils/device';

// 初始化路由
const currentDevice = initRouter();

const app = createApp(App);
app.use(router);
app.mount('#app');

// 監(jiān)聽設備變化,必要時刷新頁面
setupDeviceWatcher(newDevice => {
  if (newDevice !== currentDevice) {
    // 簡單方案:刷新頁面
    window.location.reload();
    
    // 高級方案:動態(tài)替換路由(需更復雜實現(xiàn))
    // initRouter();
    // router.push({ name: newDevice === 'mobile' ? 'MobileHome' : 'PcHome' });
  }
});

三、關鍵實現(xiàn)說明

1. 路由動態(tài)管理

  • 初始化:在應用啟動時根據(jù)設備類型加載對應路由
  • 重置機制:通過替換 router.matcher 徹底清除舊路由
  • 守衛(wèi)檢查:確保用戶不會訪問與設備不匹配的路由

2. 設備檢測策略

  • 雙重檢測:結合 User-Agent 和屏幕尺寸
  • 響應式監(jiān)聽:監(jiān)聽窗口變化,支持設備旋轉(zhuǎn)時的路由更新

3. 組件實現(xiàn)示例(移動端首頁)

<!-- views/mobile/Home.vue -->
<template>
  <div class="mobile-home">
    <!-- 移動端專屬布局 -->
    <header class="mobile-header">
      <h1>移動版首頁</h1>
      <button @click="goToCart">購物車 ({{ cartCount }})</button>
    </header>
    
    <main class="mobile-content">
      <ProductList :products="products" />
    </main>
    
    <footer class="mobile-footer">
      <nav>
        <a href="/" rel="external nofollow" >首頁</a>
        <a href="/category" rel="external nofollow" >分類</a>
        <a href="/cart" rel="external nofollow" >購物車</a>
        <a href="/profile" rel="external nofollow" >我的</a>
      </nav>
    </footer>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import ProductList from '@/components/mobile/ProductList.vue';

export default {
  components: {
    ProductList
  },
  setup() {
    const cartCount = ref(0);
    const products = ref([]);
    
    onMounted(() => {
      // 獲取商品列表和購物車數(shù)據(jù)
      fetchProducts();
      updateCartCount();
    });
    
    const goToCart = () => {
      router.push({ name: 'MobileCart' });
    };
    
    return {
      cartCount,
      products,
      goToCart
    };
  }
};
</script>

四、補充說明

1.錯誤處理

  • 添加了 404 頁面和路由不存在時的重定向邏輯
  • 路由守衛(wèi)確保用戶不會訪問與設備不匹配的頁面

2.性能優(yōu)化

  • 使用路由懶加載(() => import(...))減少初始加載時間
  • 設備類型檢測結果可緩存到 localStorage 避免重復計算

3.用戶體驗

  • 提供了設備旋轉(zhuǎn)時的處理方案(刷新頁面或動態(tài)更新路由)
  • 路由切換時可添加過渡動畫減少白屏感

這個方案實現(xiàn)了嚴格的設備隔離,確保只有對應端的代碼會被加載和執(zhí)行,適合兩端功能差異較大的應用場景。

很好,把組件切換也加進去,兩者整理下再輸出,做下對比

Vue路由切換和組件切換方法

以下是基于 Vue 的路由切換組件切換兩種適配方案的完整對比,包含目錄結構、實現(xiàn)代碼、優(yōu)缺點分析:

1.路由切換方案

1. 目錄結構

src/
├── router/
│   ├── index.js           # 主路由配置
│   ├── mobileRoutes.js    # 移動端路由
│   └── pcRoutes.js        # PC端路由
├── views/
│   ├── mobile/            # 移動端視圖
│   │   ├── Home.vue
│   │   └── Product.vue
│   └── pc/                # PC端視圖
│       ├── Home.vue
│       └── Product.vue
├── utils/
│   ├── device.js          # 設備檢測工具
│   └── storage.js         # 本地存儲工具
└── main.js                # 入口文件

2. 核心代碼

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import { mobileRoutes } from './mobileRoutes'
import { pcRoutes } from './pcRoutes'
import { detectDevice } from '@/utils/device'

const router = createRouter({
  history: createWebHistory(),
  routes: [] // 動態(tài)加載
})

export function initRouter() {
  const device = detectDevice()
  const routes = device === 'mobile' ? mobileRoutes : pcRoutes
  
  // 重置路由
  router.matcher = createRouter({
    history: createWebHistory()
  }).matcher
  
  routes.forEach(route => router.addRoute(route))
  return device
}

// main.js
import { initRouter } from './router'

// 初始化前完成路由設置
initRouter()

createApp(App).use(router).mount('#app')

2.組件切換方案

1. 目錄結構

src/
├── router/
│   └── index.js           # 統(tǒng)一路由配置
├── views/
│   ├── Home.vue           # 統(tǒng)一入口視圖
│   └── Product.vue        # 統(tǒng)一入口視圖
├── components/
│   ├── DeviceDetector.vue # 設備檢測組件
│   ├── mobile/            # 移動端組件
│   └── pc/                # PC端組件
├── utils/
│   └── device.js          # 設備檢測工具
└── main.js                # 入口文件

2. 核心代碼

// router/index.js
const routes = [
  {
    path: '/',
    component: () => import('@/views/Home.vue')
  },
  {
    path: '/product/:id',
    component: () => import('@/views/Product.vue')
  }
]

// DeviceDetector.vue
<template>
  <component :is="currentComponent" />
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue'
import { detectDevice } from '@/utils/device'

export default defineComponent({
  props: {
    mobileComponent: { type: Object, required: true },
    pcComponent: { type: Object, required: true }
  },
  setup(props) {
    const currentComponent = ref(null)
    
    onMounted(() => {
      const device = detectDevice()
      currentComponent.value = device === 'mobile' 
        ? props.mobileComponent 
        : props.pcComponent
    })
    
    return { currentComponent }
  }
})
</script>

// views/Home.vue
<template>
  <DeviceDetector
    :mobileComponent="mobileHome"
    :pcComponent="pcHome"
  />
</template>

<script>
import DeviceDetector from '@/components/DeviceDetector.vue'
import MobileHome from '@/components/mobile/Home.vue'
import PcHome from '@/components/pc/Home.vue'

export default {
  components: {
    DeviceDetector
  },
  setup() {
    return {
      mobileHome: MobileHome,
      pcHome: PcHome
    }
  }
}
</script>

3.方案對比

維度路由切換方案組件切換方案
核心邏輯在路由初始化時決定加載哪套路由在組件渲染時決定顯示哪個子組件
切換時機路由導航前(無組件渲染)組件掛載后(可能有短暫渲染)
資源加載僅加載當前設備所需資源可能同時加載多端資源
用戶體驗切換需刷新頁面(有白屏)平滑切換(無感知)
適用場景兩端功能差異大,需嚴格資源隔離兩端功能相似,僅 UI 布局不同

到此這篇關于JavaScript實現(xiàn)pc端和移動端頁面切換的兩種基本方案的文章就介紹到這了,更多相關JavaScript頁面切換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

安溪县| 肥西县| 长丰县| 寿光市| 宝兴县| 宝应县| 浦城县| 安宁市| 德钦县| 千阳县| 五家渠市| 颍上县| 福鼎市| 凤阳县| 伊金霍洛旗| 乌苏市| 石家庄市| 商河县| 三明市| 甘南县| 托克逊县| 镇赉县| 岚皋县| 泰来县| 朝阳区| 中卫市| 徐汇区| 武清区| 南充市| 西峡县| 乌审旗| 聂拉木县| 前郭尔| 澄江县| 天津市| 凯里市| 招远市| 肃南| 泰顺县| 津南区| 常州市|