Vue H5或者PC响应式配置路由

安装依赖

cnpm i @vueuse/core
/utils/flexible.js
import { PC_DEVICE_WIDTH } from '../constants'
import { computed } from 'vue'
import { useWindowSize } from '@vueuse/core'
const { width } = useWindowSize()
// 判断当前设备是否为移动设备,判断依据屏幕宽度是否小于一个指定宽度(900)
export const isMobileTerminal = computed(() => {
  // console.log(width.value, document.body.clientWidth)
  return width.value < 900
})

移动端路由示例:

/router/modules/mobile-routes.js

import mHome from '@/pages/mHome.vue'
import mHomePage from '@/pages/mHomePage/index.vue'

export const mobileRoutes = [
  {
    path: '/',
    component: mHome,
    redirect: '/HomePage ',
    children: [
      {
        path: '/HomePage',
        name: 'HomePage',
        component: mHomePage
      }
    ]
  },
]

PC端路由示例:

/router/modules/pc-router.js

import Home from '@/views/Home.vue'
import HomePage from '@/views/homePage/index.vue'

export const mobileRoutes = [
  {
    path: '/',
    component: Home ,
    redirect: '/homePage',
    children: [
      {
        path: '/HomePage',
        name: 'HomePage',
        component: HomePage
      }
    ]
  },
]

导入路由和配置文件

/router/index.js

import { createRouter, createWebHistory } from 'vue-router'
import { isMobileTerminal } from '@/utils/flexible.js'
import { mobileRoutes } from '@/router/modules/mobile-routes.js'
import { pcRouter } from '@/router/modules/pc-router.js'

const routes = isMobileTerminal.value ? mobileRoutes : pcRouter
const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

你可能感兴趣的:(vue,vue.js,javascript,ecmascript)