1、安装 Vue Router:
在 Vue 3 项目中,你首先需要确保安装了 Vue Router。你可以使用 npm 或 yarn 来安装:
npm install vue-router@next
# 或
yarn add vue-router@next
2、在src目录下创建 router/index.ts
文件:
在你的项目中创建一个 router
目录,然后在该目录下创建 index.ts
文件。这个文件将包含路由的配置。
3、配置路由:
在 index.ts
文件中,使用 createRouter
函数创建一个新的路由实例。定义路由的配置,包括路由的路径、名称和对应的组件。
// router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: About,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
4、在 main.ts 中使用路由:
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router).mount('#app');//路由挂载
5、在组件中使用路由:
在需要使用路由的组件中,可以使用 <router-link>
创建链接,使用 to
属性指定目标路径。同时,使用 <router-view>
渲染当前路由对应的组件。
<!-- 在组件中使用路由链接 -->
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<!-- 渲染当前路由对应的组件 -->
<router-view></router-view>