Vue 路由(Vue Router)详解:轻松实现单页应用导航
Vue 路由(Vue Router)详解:轻松实现单页应用导航
Vue 是一个构建用户界面的渐进式框架,配合 Vue Router 后可以轻松开发功能丰富的 单页应用(SPA)。本篇文章将深入介绍 Vue Router 的原理、使用方式、常见配置和进阶技巧,帮助你彻底掌握 Vue 应用的“导航引擎”。
一、什么是 Vue Router?
Vue Router 是 Vue.js 官方的路由管理器。它的核心功能是:在不刷新页面的情况下,根据 URL 的变化动态加载组件,实现页面切换效果。
例如,我们访问 /home
时显示首页组件,访问 /about
时显示关于页组件。
二、Vue Router 的安装与引入
2.1 安装
npm install vue-router
对于 Vue 3:
npm install vue-router@4
2.2 引入并配置
以 Vue 3 为例:
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'const routes = [{ path: '/', component: Home },{ path: '/about', component: About }
]const router = createRouter({history: createWebHistory(),routes
})export default router
2.3 在应用中挂载
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'createApp(App).use(router).mount('#app')
三、基本使用示例
3.1 路由视图与链接
在 App.vue
中使用:
<template><nav><router-link to="/">首页</router-link> |<router-link to="/about">关于</router-link></nav><router-view />
</template>
router-link
是跳转链接组件router-view
是路由组件的“出口”,匹配到的组件将显示在这里
四、常见路由配置项详解
4.1 动态路由
{ path: '/user/:id', component: User }
在组件中获取参数:
setup(props, { route }) {console.log(route.params.id)
}
4.2 嵌套路由
{path: '/parent',component: Parent,children: [{ path: 'child', component: Child }]
}
在 Parent.vue
中使用 <router-view />
来显示子路由组件。
4.3 重定向与别名
{ path: '/home', redirect: '/' }
{ path: '/index', alias: '/' }
五、编程式导航
5.1 使用 router.push
this.$router.push('/about')
或 Vue 3 的组合式写法:
import { useRouter } from 'vue-router'
const router = useRouter()
router.push('/about')
5.2 replace
替代当前历史记录
router.replace('/login')
六、路由守卫(导航守卫)
Vue Router 提供了全局、路由独享和组件内守卫,可用于登录验证、权限判断等场景。
6.1 全局前置守卫
router.beforeEach((to, from, next) => {if (to.path === '/admin' && !isAuthenticated()) {next('/login')} else {next()}
})
6.2 路由独享守卫
{path: '/admin',component: Admin,beforeEnter: (to, from, next) => {// 权限校验逻辑}
}
七、懒加载路由组件
Vue Router 支持动态引入组件:
{path: '/about',component: () => import('../views/About.vue')
}
优点是:打包文件更小、初始加载更快。
八、404 页面与通配符路由
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }
通配符 *
匹配所有未知路径,可用作 404 页面。
九、使用命名路由与命名视图
9.1 命名路由
{ path: '/user/:id', name: 'user', component: User }
router.push({ name: 'user', params: { id: 123 } })
9.2 命名视图
{path: '/layout',components: {default: Main,sidebar: Sidebar}
}
配合模板中:
<router-view /> <!-- default -->
<router-view name="sidebar" />
十、Hash 模式 vs History 模式
模式 | 特点 | 地址格式 |
---|---|---|
Hash | 使用 # ,兼容性更强 | /#/about |
History | 更美观,需后端配置支持 | /about |
创建 router 时设置:
createWebHashHistory() // Hash 模式
createWebHistory() // History 模式
十一、进阶技巧
11.1 滚动行为控制
const router = createRouter({history: createWebHistory(),routes,scrollBehavior(to, from, savedPosition) {return savedPosition || { top: 0 }}
})
11.2 路由元信息(meta)
{ path: '/admin', meta: { requiresAuth: true } }
结合守卫使用:
router.beforeEach((to, from, next) => {if (to.meta.requiresAuth && !isLoggedIn()) {next('/login')} else {next()}
})
十二、总结
Vue Router 作为单页应用的导航核心,具备以下能力:
✅ URL 与组件的映射
✅ 路由参数与嵌套路由
✅ 导航守卫保障安全性
✅ 编程式跳转与懒加载优化
✅ 多视图、命名路由提升灵活性
通过合理配置 Vue Router,我们可以构建出结构清晰、用户体验流畅的单页应用。