> For the complete documentation index, see [llms.txt](https://close.gitbook.io/yun-wei-bi-ji/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://close.gitbook.io/yun-wei-bi-ji/centos/vue/xiang-mu/1-04.-yin-ru-vue-router4-lu-you-pei-zhi-he-404-ye-mian-bu-huo.md).

# 1 04.引入vue router4路由配置和404页面捕获

> [安装 | Vue Router](https://router.vuejs.org/zh/installation.html)

* #### 安装

```js
npm install vue-router@4
```

* #### 项目下 src 目录下创建 router 文件夹，并创建主路由文件 index.js

```js
// src/router/index.js


import {
    createRouter,
    createWebHashHistory
} from 'vue-router'


// 2.定义一些路由
const routes = []


// 3.创建路由实例并传递 `routes` 配置
const router = createRouter({
    history: createWebHashHistory(),
    routes
}) 


// 4.暴露出去
export default router
```

* 应用到项目入口文件 main.js

```js
import router from './router'
'''略
app.use(router)
```

* #### 路由配置

```js
// 自定义路由读取路径配置： vite.config.js
import path from 'path'             // +

export default defineConfig({
  resolve: {
    alias: {
      "~": path.resolve(__dirname,"src") // + 
    }
  },
  ...略
  
})
```

* #### src 下创建路由文件夹 pages，把所有路由放在这个文件夹内
  * pages/index.vue 首页
  * pages/about.vue 关于页
  * pages/404.vue 404页

```js
// src/pages/index.vue
<template>
    <div>
        后台首页
    </div>
</template>


// src/pages/about.vue
<template>
    <div>
        关于页
    </div>
</template>


// src/pages/404.vue
<template>
    <div>
        <el-result
            icon="warning"
            title="404提示"
            sub-title="你找的页面走丢了"
        >
            <template #extra>
            <el-button type="primary" @click="$router.push('/')">
                回到首页
            </el-button>
            </template>
        </el-result>
    </div>
</template>
```

* #### 引入刚刚创建的三个组件到 router/index.js

```js
...略
import Index from '~/pages/index.vue'  // +
import About from '~/pages/about.vue'  // +
import NotFound from '~/pages/404.vue' // + 

// 2.定义一些路由
const routes = [
    { path: "/", component: Index, name: "index"},      // +
    { path: "/about", component: About, name: "about"}, // +
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }, // + 404 Not found 路由
]


```

* #### 修改 App.vue, 使路由生效

```js
<script setup>

</script>

<template>
  <router-view></router-view>  // +
</template>

<style>
</style>


```

* ### 最终代码

<div><img src="C:%5CUsers%5CAdministrator.DESKTOP-UK43ECI%5CAppData%5CRoaming%5Cmarktext%5Cimages%5C2023-02-16-15-10-15-image.png" alt=""> <figure><img src="https://2134947750-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvILwbD2PrkBCkSitM3m4%2Fuploads%2FBLxlFiKSiAiL8yRFQynH%2F2023-02-16-15-10-15-image.png?alt=media&amp;token=002f1b0a-59ad-4afc-9267-ac96123f5c4c" alt=""><figcaption></figcaption></figure></div>
