开篇:为什么说路由是SPA应用的「导航仪」?
现代Web应用就像多层宇宙,每个页面都是独立维度! Vue Router 正是穿梭不同维度的传送门:
✅ 页面无刷新跳转——告别白屏等待
✅ 路由守卫——权限控制的钢铁侠战甲
✅ 动态路由——让页面按需加载
✅ 历史模式——抹去URL中的#
魔法印记
npm install vue-router@4 # Vue 3项目
# 或
npm install vue-router@3 # Vue 2项目
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue')
},
{
path: '/about',
name: 'About',
component: () => import('@/views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
在App.vue中放置传送门接收器:
使用
关于我们
配置带参数的路由(电商产品页示例):
{
path: '/product/:id',
name: 'Product',
component: ProductDetail,
props: true // 将params转为props
}
// 全局前置守卫
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
next('/login') // 拦截未登录用户
} else {
next()
}
})
// 路由配置中添加元数据
{
path: '/dashboard',
meta: { requiresAuth: true }
}
// 使用import实现懒加载
{
path: '/admin',
component: () => import('@/views/AdminPanel.vue')
}
{
path: '/user',
component: UserLayout,
children: [
{ path: 'profile', component: UserProfile },
{ path: 'settings', component: UserSettings }
]
}
⚠️ 路由跳转后页面空白
⚠️ 动态路由参数不更新
⚠️ 路由模式选择困难症
模式 | 特点 |
---|---|
createWebHashHistory | URL带#,兼容性好(默认) |
createWebHistory | 干净URL,需服务器配合 |
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
// 动态注册路由
const adminRoutes = await fetch('/api/admin-routes')
router.addRoute(adminRoutes)
// 在首页加载完成后预加载其他路由
onMounted(() => {
import('@/views/ProductList.vue')
})
互动环节
你在使用Vue Router时遇到过哪些"灵异事件"?欢迎在评论区分享你的填坑经验!
✨ 让路由不再迷路,开启你的丝滑SPA之旅吧!