pc端配套移动端(一)


pc 端配套移动端(一)

公司 PC 端适配移动端,以下是方法其一,根据视口大小,改变路由配置。这是一个方向

// router

import { createRouter, createWebHistory } from 'vue-router'
import { ref, watch } from 'vue'
// @ts-ignore
import Index from '@/views/dashboard/index.vue'

const pcRoutes = [
  // ... 保持原有 pcRoutes 配置不变 ...
]

const mobileRoutes = [
  // 建议添加移动端路由配置,而不是空数组
  {
    path: '/',
    name: 'mobile-dashboard',
    component: () => import('@/views/mobile/index.vue'),
  },
  // ... 其他移动端路由
]

// 创建响应式的窗口宽度
const windowWidth = ref(window.innerWidth)

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: windowWidth.value >= 1024 ? pcRoutes : mobileRoutes,
})

// 监听窗口大小变化
const handleResize = () => {
  windowWidth.value = window.innerWidth
  updateRoutes()
}

// 更新路由配置
const updateRoutes = () => {
  // 获取当前路由路径
  const currentPath = router.currentRoute.value.path

  // 清除现有路由
  router.getRoutes().forEach((route) => {
    if (route.name) {
      router.removeRoute(route.name)
    }
  })

  // 添加新路由
  const newRoutes = windowWidth.value >= 1024 ? pcRoutes : mobileRoutes
  newRoutes.forEach((route) => {
    router.addRoute(route)
  })

  // 重新导航到当前页面以触发路由更新
  router.replace(currentPath)
}

// 添加防抖处理
const debounce = (fn, delay) => {
  let timer = null
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay)
  }
}

// 使用防抖处理的 resize 事件监听
window.addEventListener('resize', debounce(handleResize, 200))

// 初始化检查
handleResize()

export default router
app.vue

<template>
  <div class="app">
    <router-view v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <component :is="Component" />
      </transition>
    </router-view>
  </div>
</template>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
router

// 在 updateRoutes 函数中添加加载状态
const isRouteUpdating = ref(false)

const updateRoutes = async () => {
  try {
    isRouteUpdating.value = true
    const currentPath = router.currentRoute.value.path

    // 清除现有路由
    router.getRoutes().forEach((route) => {
      if (route.name) {
        router.removeRoute(route.name)
      }
    })

    // 添加新路由
    const newRoutes = windowWidth.value >= 1024 ? pcRoutes : mobileRoutes
    newRoutes.forEach((route) => {
      router.addRoute(route)
    })

    await router.replace(currentPath)
  } catch (error) {
    console.error('路由更新失败:', error)
    // 可以添加错误提示或跳转到错误页面
  } finally {
    isRouteUpdating.value = false
  }
}

文章作者: 冷杨威
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 冷杨威 !
  目录
-->