在 Vue3 中使用 Vite 自动生成路由

记录下在 Vue3 中使用 Vite 自动生成路由

安装依赖

1
npm install vue-router@4 --save

目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
src
- router
- index.js
- views
- about
- index.vue
- page.js
- contact
- index.vue
- page.js
- error
- index.vue
- page.js
- index.vue
- page.js
- App.vue
- main.js

router/index.js: 路由配置
views/about: 匹配 /about (path与目录名称一致)
views/contact: 匹配 /contact(path与目录名称一致)
views/error: path未匹配时的处理,比如404
**/page.js: 约定配置,导出比如 meta 等默认数据
**/index.vue: 约定组件

为了以后可能要新增的path,需要做一个约定

比如匹配 /login,需创建一个与 /login 同名的 src/views/login 目录,它也要有 index.vuepage.js 两个文件

代码

路由配置

router/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { createRouter, createWebHistory } from "vue-router"

const coms = import.meta.glob("../views/**/index.vue")
const pages = import.meta.glob("../views/**/page.js", {
eager: true,
import: "default"
})

const routes = Object.entries(pages).map(([path, meta]) => {
const comPath = path.replace("page.js", "index.vue")
path = path.replace("../views", "").replace("/page.js", "") || "/"
const name = path.split("/").filter(Boolean).join("-") || "index"
if (path === "/error") {
path = "/:error*"
}
return {
path,
name,
component: coms[comPath],
meta
}
})

const router = createRouter({
history: createWebHistory(),
routes
})

router.beforeEach((to, from, next) => {
document.title = to.meta.title
next()
})

export default router

main.js 配置

1
2
3
4
5
6
7
8
import { createApp } from "vue"

import App from "./App.vue"
import router from "./router/index"

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

App.vue 配置

1
2
3
4
5
6
7
<template>
<router-link to="/">首页 | </router-link>
<router-link to="/about">关于 | </router-link>
<router-link to="/contact">联系</router-link>
<br />
<router-view></router-view>
</template>

首页页面配置

views/index.vue

1
2
3
<template>
<p>首页</p>
</template>

views/page.js

1
2
3
export default {
title: "首页"
}

关于页面配置

views/about/index.vue

1
2
3
<template>
<p>关于</p>
</template>

views/about/page.js

1
2
3
export default {
title: "关于"
}

联系页面配置

views/contact/index.vue

1
2
3
<template>
<p>联系</p>
</template>

views/contact/page.js

1
2
3
export default {
title: "联系"
}

404页面配置

views/error/index.vue

1
2
3
<template>
<p>404</p>
</template>

views/error/page.js

1
2
3
export default {
title: "404未找到"
}

打包部署后直接访问子路由报错404

出现404可能原因:

  • 直接访问 https://xxx/abouthttps://xxx/contatc
  • <router-link target="_blank">target="_blank" 属性,点击会跳转新页面

解决方法
在服务器 Nginx 配置文件中添加:

1
2
3
location / {
try_files $uri $uri/ /index.html;
}

然后重启 Nginx 服务

资料