1. 引入 vue-router 的 js 库
npm install vue-router@4
2. 从其他文件导入路由组件
import Index from "@/pages/Index.vue";
import Team from "@/pages/Team.vue";
3. 定义路由,每个路由都需要映射到一个组件
routes: [
{
path: '/',
name: 'home',
component: Index
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/AboutView.vue')
},
{
path: '/team',
name: '队伍',
component: Team
}
]
4. 创建路由实例,并导出 router 配置
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: Index
},
]
})
export default router
5. 创建并挂载根实例(一般创建项目时就创建好了)
// 创建
const app = createApp(App)
// 使用路由实例,确保整个应支持路由
app.use(router)
// 挂载
app.mount('#app')
6. 使用 router-view 组件指定路由对应组件的渲染位置(可以看成一个占位符)
<div id="content">
<router-view></router-view>
</div>
7. 使用 router-link 组件进行导航,to 属性指定跳转链接
<router-link to="/">Go to Home</router-link>
<router-link to="/team">队伍</router-link>
8. 底部标签栏添加路由
- Vant 组件库整合了 Vue-Router,直接使用 Vant 组件库的路由功能
9. 查看效果