vue3 【提效】自动路由(含自定义路由) unplugin-vue-router 实用教程

发布于:2024-06-28 ⋅ 阅读:(17) ⋅ 点赞:(0)

不再需要为每一个路由编写冗长的 routes 配置啦,新建文件便可自动生成路由!

使用方法

1. 安装 unplugin-vue-router

npm i -D unplugin-vue-router

2. 修改 vite 配置

vite.config.ts

import VueRouter from 'unplugin-vue-router/vite'

plugins 中加入 VueRouter ,注意其必须在 vue() 之前

  plugins: [
    // VueRouter  必须在 vue() 之前
    VueRouter({}),
    vue(),
    vueJsx(),
    vueDevTools()
  ],

3. 修改路由配置

src/router/index.ts

import { createRouter, createWebHistory } from 'vue-router'
import { routes } from 'vue-router/auto-routes'
const router = createRouter({
  history: createWebHistory(),
  routes
})
export default router

src/App.vue 中为

<template>
  <RouterView />
</template>
  • 组件 RouterView 和 RouterLink 都是全局注册的,因此无需导入。见官网

自动路由规则

默认情况下,会为 src/pages 中的文件自动创建路由(可以通过配置修改为其他目录,但不建议这么做)

推荐的页面目录结构 :

在这里插入图片描述

自动路由效果为 :

路由 文件
/ pages/index.vue
/about pages/about.vue
/users pages/users/index.vue
/users/1 pages/users/[id].vue
/other pages/[…404].vue
  • index.vue 的路由为 / 不是 /index
  • [id].vue 会得到动态路由,与 vue-router 中的 /:id 效果相同

比如 [id].vue 的内容为

<script setup lang="ts">
import { useRoute } from 'vue-router'
const route = useRoute()
</script>

<template>
  <div>用户详情</div>
  <p>id:{{ route.params.id }}</p>
</template>

<style scoped lang="scss"></style>

则访问 http://localhost:5173/users/1 的效果为:

用户详情
id:1
  • […404].vue 用于匹配所有不存在的路由,内容通常为 404 页面。
<template>
  <div>404</div>
</template>
[...404].vue 中的 404 也可以自定义为任意其他的字符串,如 path,all 等,效果一样,此处为了方便识别为 404 页面,用的 404

自定义路由

当自动路由无法满足需求时,可以参考下方代码自定义路由

src/router/index.ts

import { createRouter, createWebHistory } from 'vue-router'
import { routes } from 'vue-router/auto-routes'
const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...routes,
    // 自定义配置路由 /test ,访问文件 src/views/test.vue
    {
      path: '/test',
      component: () => import('@/views/test.vue')
    }
  ]
})
export default router

更多配置和用法见官网

https://uvr.esm.is/guide/configuration.html


网站公告

今日签到

点亮在社区的每一天
去签到