vue3+ts+vite配置路由
时间: 2023-08-27 07:22:53 浏览: 143
在 Vue 3 中使用 TypeScript 并结合 Vite 构建工具来配置路由,可以按照以下步骤进行操作:
1. 首先,确保你已经创建了一个 Vue 3 项目,并且已经安装了相关依赖。可以通过以下命令创建一个新的 Vue 3 项目:
```
$ npm init vite@latest my-vue3-app --template vue-ts
$ cd my-vue3-app
$ npm install
```
2. 安装 Vue Router 和相关 TypeScript 类型定义:
```
$ npm install vue-router@next
$ npm install @types/vue-router
```
3. 在 `src` 目录下创建一个新的文件夹,比如 `router`,并在其中创建一个名为 `index.ts` 的文件,用于配置路由。
4. 在 `index.ts` 文件中,首先引入 Vue Router 和相关组件:
```typescript
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
```
5. 声明一个 `routes` 数组,用于定义路由配置:
```typescript
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: About,
},
];
```
在这个例子中,我们定义了两个路由:`'/'` 对应到 `Home` 组件,`'/about'` 对应到 `About` 组件。
6. 创建一个路由实例,并且将路由配置传递给它:
```typescript
const router = createRouter({
history: createWebHistory(),
routes,
});
```
这里使用了 `createWebHistory()` 来创建一个基于 HTML5 History API 的路由模式。
7. 最后,将路由实例导出,以便在 Vue 应用中使用:
```typescript
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)