# 路由配置

## 1.创建路由

首先在`main.js`文件中引入`vue-router`和路由对象，之后将路由配置挂载到根实例中

```javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter) //挂载到vue对象中
import router from '@/routers/' //路由配置对象

new Vue({
  router, //挂载到根实例对象app上，这里必须叫router，也可以router:其他名字
  render: (h) => h(App),
}).$mount('#app')
```

## 2.批量注册路由

首先在`routers`文件夹中包含所有的路由文件

```bash
--common.js 通用路由配置文件
--people.js 具体项目路由文件
--index.js 引入其他路由文件
```

在`index.js`中引入所有的路由文件

```javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

let routes = []
const requireContext = require.context('./', true, /\.js$/) //加载其他路由文件
requireContext.keys().forEach((filename) => {
  if (filename === './index.js') {
    return
  }
  const routeModule = requireContext(filename) // 获取文件内容
  routes = [...routes, ...routeModule.default] // 合并两个数组内容
})
const router = new VueRouter({
  routes,
})  //生成router实例

//最后添加404守卫路由
router.addRoutes([
  {
    path: '*',
    name: '404',
    component: () => import('@/views/404.vue'),
  },
])

//配置全局路由守卫
router.beforeEach((to, from, next) => {
  Nprogress.start()
  document.title = from.meta.title
  next()
})
router.afterEach((to, from) => {
  console.log(from.name)
  document.title = to.meta.title
  Nprogress.done()
})
export default router
```

## 3.路由配置

例如我在`common.js`文件中，配置了项目中通用的一些路由；包括404页面等。

```javascript
export default [
  {
    path: '/404',
    name: 'pge404',
    component: () => {
      return import('../views/404.vue') //引入404组件
    },
    meta: { title: '404' },
  },
]
```

在这里我遇到了一个不起眼的小问题，就是在使用箭头函数导入404组件的时候，没有用return导致这个路由无效了

> 错误代码

`component: () => { import('../views/404.vue') //引入404组件 },`

## 4.配置切换路由动画


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zpliu.gitbook.io/booknote/cottonweb/3.-pei-zhi-qian-duan-lu-you.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
