在 Vue 3 中使用 Vue Router 时,通常需要在 App.vue 文件中添加一个 <router-view> 组件。这个组件是 Vue Router 提供的特殊组件,它会根据当前的路由显示不同的视图内容。
一、在 Vue 3 中导入并配置 Vue Router 的步骤如下:
1、安装 Vue Router:
确保已经安装了 Vue Router 的最新版本。对于 Vue 3,你需要安装 Vue Router 4.x 版本。
2、创建路由配置文件:
通常会在 src/router 文件夹下创建一个 index.js 文件,用于配置路由。
3、配置路由:
在 index.js 文件中,使用 Vue Router 提供的 API 来定义路由规则。
4、注册路由到主应用:
在主应用文件中(通常是 main.js 或 main.ts),导入并注册 Vue Router。
二、详细步骤——示例代码
1、安装 Vue Router:
如果你还没有安装 Vue Router,请先安装它。
npm install vue-router@4
2、配置路由:
创建路由配置文件(例如 src/router/index.js),并在其中定义路由规则。
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
// 导入组件
import HelloWorld from '../components/HelloWorld.vue';
// 定义路由
const routes = [
{ path: '/', component: HelloWorld },
];
// 创建路由器实例
const router = createRouter({
history: createWebHistory(),
routes,
});
// 导出路由器
export default router;
3、注册路由到主应用
在 main.js 或 main.ts 中注册路由,导入并使用路由。
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'; // 导入路由配置
// createApp(App).mount('#app')
const app = createApp(App);
// 使用路由
app.use(router);
// 挂载根组件
app.mount('#app');
4、在 App.vue 中使用 <router-view>:
在 App.vue 中添加 <router-view> 组件。
<template>
<router-view></router-view>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
说明
<router-view> 组件是 Vue Router 的核心组件之一,它负责根据当前激活的路由渲染对应的组件。
你可以根据需要在 App.vue 中放置 <router-view>,通常将其放在应用的主要内容区域。
使用 <router-link>
<router-link> 是 Vue Router 提供的另一个组件,用于创建导航链接。在上面的示例中,我们在 App.vue 的模板中使用了 <router-link> 组件来创建导航链接。