Vue3 路由组件练习
1. 演示效果
2. 代码分析
2.1. 安装 vue-router
命令:npm i vue-router
应用插件:Vue.use(VueRouter)
2.2. 创建路由文件
在 src 文件夹下,创建router 文件夹,并在该文件夹创建index.js
文件
2.3. 创建路由实例
使用 createRouter
函数创建一个路由器实例,并传入一个 history 参数,该参数是一个用于记录路由变更的 history 对象。
这里使用了环境变量 BASE_URL
,从 import.meta.env.BASE_URL
中获取基础 URL。
组件的加载方式是通过闭包实现。在每个路由对象中,使用 component: () => import("../components/{componentName}.vue")
加载组件。
js
import { createRouter, createWebHistory } from "vue-router";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "/useHook",
name: "useHook",
component: () => import("../components/UseHooks.vue"),
},
{
path: "/musicList",
name: "musicList",
component: () => import("../components/MusicList.vue"),
},
{
path: "/purchaseCar",
name: "purchaseCar",
component: () => import("../components/PurchaseCar.vue"),
},
],
});
export default router;
2.4. 使用 router-link 组件导航
在App.vue 文件中,我们使用 router-link
组件导航,通过传入 to
属性指定链接。<router-link>
默认会被渲染成一个 <a>
标签
在 <router-view>
标签中,我们使用了默认的路由组件。当你点击路由链接时,Vue Router 会根据指定的目标路由渲染相应的路由组件。
js
<template>
<div class="wrapper">
<router-link to="/" style="margin-right: 10px;">Go to Home</router-link><br>
<router-link to="/musicList">Go to MusicList</router-link><br>
<router-link to="/purchaseCar">Go to PurchaseCar</router-link><br>
<router-link to="/useHook">Go to UseHook</router-link><br>
</div>
<br /><br />
<router-view>
</router-view>
</template>
<script setup>
</script>
<style scoped>
#wrapper {
width: 100vw;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
margin: 0 auto;
}
</style>
3. 代码实现
3.1. index.js 文件
js
import { createRouter, createWebHistory } from "vue-router";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "/useHook",
name: "useHook",
component: () => import("../components/UseHooks.vue"),
},
{
path: "/musicList",
name: "musicList",
component: () => import("../components/MusicList.vue"),
},
{
path: "/purchaseCar",
name: "purchaseCar",
component: () => import("../components/PurchaseCar.vue"),
},
],
});
export default router;
3.2. App 文件
js
<template>
<div class="wrapper">
<router-link to="/" style="margin-right: 10px;">Go to Home</router-link><br>
<router-link to="/musicList">Go to MusicList</router-link><br>
<router-link to="/purchaseCar">Go to PurchaseCar</router-link><br>
<router-link to="/useHook">Go to UseHook</router-link><br>
</div>
<br /><br />
<router-view>
</router-view>
</template>
<script setup>
</script>
<style scoped>
#wrapper {
width: 100vw;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
margin: 0 auto;
}
</style>