Vue Router 学习笔记
一、声明式路由
1. 创建Vue工程
bash
npm create vite
2. 更新依赖
bash
cd 工程目录
npm install
3. 安装路由
bash
npm install vue-router
4. 配置路由
在 src 文件夹中新建 routers 文件夹,再新建 router.js 文件:
javascript
// 导入创建路由的方法
import { createRouter, createWebHashHistory } from 'vue-router'
// 导入组件
import Home from '../components/Home.vue'
import List from '../components/List.vue'
import Add from '../components/Add.vue'
// 定义路由
const routes = [
{ path: '/', redirect: '/home' }, // 重定向
{ path: '/home', component: Home },
{ path: '/list', component: List },
{ path: '/add', component: Add },
]
// 创建路由实例
const router = createRouter({
history: createWebHashHistory(), // 哈希模式
routes
})
export default router
5. 准备页面组件
components/Home.vue
vue
Home页面
List.vue 和 Add.vue 结构相同,只需修改标题内容。
6. 注册路由(main.js)
javascript
import { createApp } from 'vue'
import App from './App.vue'
import router from './routers/router.js' // 导入路由对象
const app = createApp(App)
app.use(router) // 挂载路由
app.mount('#app')
7. 使用路由(App.vue)
vue
编程式路由:通过 useRouter 动态决定跳转路径,更灵活。
核心API
useRouter():返回 router 对象
router.push('/path'):导航到新页面
router.back():返回上一页
router.go(n):前进/后退 n 步
案例:通过按钮实现路由跳转
App.vue
vue
守卫类型
类型 执行时机 配置位置
全局前置守卫 路由切换前 router.js
全局后置守卫 路由切换后 router.js
路由独享守卫 进入特定路由前 路由配置中
组件内守卫 组件内 组件文件中
1. 全局前置守卫
javascript
// router.js 中配置
// 全局前置路由守卫
router.beforeEach((to, from, next) => {
// to : 目标路由对象(可用 to.path 获取路径)
// from : 来源路由对象(可用 from.path 获取路径)
// next : 方法,不调用则默认拦截
console.log(to.path, from.path)
// 判断逻辑,注意避免无限重定向
if (to.path == '/index') {
next() // 放行,到达目标组件
} else {
next('/index') // 重定向到其他地址(会再次经过前置守卫)
}
})
2. 全局后置守卫
javascript
// router.js 中配置
// 全局后置路由守卫
router.afterEach((to, from) => {
console.log(Navigate from ${from.path} to ${to.path})
// 可用于:日志记录、页面标题更新、DOM操作等
})
完整 router.js 示例(含守卫)
javascript
import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../components/Home.vue'
import List from '../components/List.vue'
import Add from '../components/Add.vue'
const routes = [
{ path: '/', redirect: '/home' },
{ path: '/home', component: Home },
{ path: '/list', component: List },
{ path: '/add', component: Add },
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
// 示例:检查登录状态
const isLogin = localStorage.getItem('token')
if (to.path !== '/login' && !isLogin) {
next('/login') // 未登录且访问非登录页,跳转登录
} else {
next() // 放行
}
})
// 全局后置守卫
router.afterEach((to, from) => {
// 更新页面标题
document.title = to.meta.title || '默认标题'
})
export default router
典型应用场景
守卫类型 典型用途
beforeEach 登录验证、权限检查、页面访问控制
afterEach 页面埋点日志、标题更新、滚动行为
路由独享守卫 特定页面的权限验证
组件内守卫 进入/离开组件前的确认操作
浙公网安备 33010602011771号