🎉 Vue2 路由缓存与导航控制最佳实践

This commit is contained in:
bunny 2025-06-22 20:18:10 +08:00
parent 90e512b977
commit b73a52c022
3 changed files with 180 additions and 149 deletions

View File

@ -1,148 +0,0 @@
# Vue Router 路由管理与导航控制指南
## 一、路由导航核心方法
### 1. 编程式导航 API
| 方法 | 说明 | 示例 |
| --------- | --------------------- | -------------------------------- |
| `push` | 添加新路由记录 | `this.$router.push('/about')` |
| `replace` | 替换当前路由 | `this.$router.replace('/login')` |
| `go` | 在历史记录中前进/后退 | `this.$router.go(-1)` |
| `back` | 后退一步 | `this.$router.back()` |
| `forward` | 前进一步 | `this.$router.forward()` |
### 2. 命名路由使用
```javascript
// 路由配置
{
path: '/about',
name: 'About', // 命名路由
component: About
}
// 导航使用
this.$router.push({ name: 'About' })
```
## 二、最佳实践建议
### 1. 导航封装方案
```javascript
// utils/navigation.js
export const navTo = (name, params = {}) => {
router.push({ name, params })
}
// 组件中使用
import { navTo } from '@/utils/navigation'
methods: {
goToAbout() {
navTo('About')
}
}
```
### 2. 导航守卫整合
```javascript
// 全局前置守卫
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
next({ name: 'Login' })
} else {
next()
}
})
```
### 3. 路由懒加载
```javascript
// 路由配置优化
const routes = [
{
path: '/about',
component: () => import('@/views/About.vue')
}
]
```
## 三、高级路由模式
### 1. 动态路由匹配
```javascript
// 路由配置
{
path: '/user/:id',
component: User
}
// 组件中获取参数
this.$route.params.id
```
### 2. 嵌套路由实践
```javascript
const routes = [
{
path: '/dashboard',
component: Dashboard,
children: [
{ path: 'profile', component: Profile },
{ path: 'settings', component: Settings }
]
}
]
```
### 3. 路由过渡动画
```html
<transition name="fade" mode="out-in">
<router-view></router-view>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
```
## 四、常见问题解决方案
1. **路由重复导航错误**
```javascript
// 捕获重复导航错误
this.$router.push('/path').catch(err => {
if (err.name !== 'NavigationDuplicated') {
console.error(err)
}
})
```
2. **页面刷新参数丢失**
```javascript
// 使用query代替params
this.$router.push({ path: '/user', query: { id: 123 } })
```
3. **滚动行为控制**
```javascript
const router = new VueRouter({
scrollBehavior(to, from, savedPosition) {
return savedPosition || { x: 0, y: 0 }
}
})
```
## 五、与Vue3 Router对比
| 特性 | Vue2 Router | Vue3 Router |
| --------- | ------------------ | ----------------------------- |
| 创建方式 | `new VueRouter()` | `createRouter()` |
| 历史模式 | `mode: 'history'` | `history: createWebHistory()` |
| 路由匹配 | 基于path-to-regexp | 基于正则表达式 |
| 组合式API | 需要额外配置 | 原生支持 |

View File

@ -0,0 +1,175 @@
# Vue2 路由缓存与导航控制最佳实践
## 一、Keep-Alive 路由缓存机制
### 1. 基本使用方式
```html
<!-- 缓存单个组件 -->
<keep-alive include="Home">
<router-view/>
</keep-alive>
<!-- 缓存多个组件 -->
<keep-alive :include="['Home', 'About']">
<router-view/>
</keep-alive>
```
### 2. 核心属性说明
| 属性 | 类型 | 说明 |
| --------- | ------------------- | ---------------------- |
| `include` | String/Regexp/Array | 匹配的组件名将被缓存 |
| `exclude` | String/Regexp/Array | 匹配的组件名不会被缓存 |
| `max` | Number | 最大缓存组件数 |
## 二、组件生命周期变化
### 1. 缓存状态下的生命周期
```
首次加载created → mounted → activated
离开组件deactivated
再次进入activated
```
### 2. 新增生命周期钩子
```javascript
export default {
activated() {
// 组件被激活时调用
this.fetchData()
},
deactivated() {
// 组件被停用时调用
this.clearTimer()
}
}
```
## 三、最佳实践建议
### 1. 缓存策略优化
```html
<!-- 动态决定是否缓存 -->
<keep-alive :include="cachedViews">
<router-view :key="$route.fullPath"/>
</keep-alive>
<script>
computed: {
cachedViews() {
return this.$store.state.tagsView.cachedViews
}
}
</script>
```
### 2. 数据刷新方案
```javascript
// 方案1监听路由变化
watch: {
'$route'(to, from) {
if (to.name === 'Home') {
this.refreshData()
}
}
}
// 方案2使用activated钩子
activated() {
this.loadData()
}
```
### 3. 内存管理技巧
```javascript
// 清除缓存数据
deactivated() {
this.list = []
this.pagination = { page: 1, size: 10 }
}
```
## 四、高级应用场景
### 1. 多级路由缓存
```javascript
// 父路由配置
{
path: '/nested',
component: Layout,
children: [
{
path: 'child1',
component: Child1,
meta: { keepAlive: true }
},
{
path: 'child2',
component: Child2
}
]
}
// 动态缓存
<keep-alive>
<router-view v-if="$route.meta.keepAlive"/>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"/>
```
### 2. 滚动位置保持
```javascript
// router配置
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else if (to.meta.keepAlive) {
return { x: 0, y: to.meta.scrollTop || 0 }
}
return { x: 0, y: 0 }
}
// 组件内记录位置
deactivated() {
this.$route.meta.scrollTop = document.documentElement.scrollTop
}
```
### 3. 缓存状态管理
```javascript
// 动态移除缓存
this.$vnode.parent.componentInstance.cache = {}
this.$vnode.parent.componentInstance.keys = []
```
## 五、常见问题解决方案
1. **缓存不生效排查**
- 检查组件`name`是否与`include`匹配
- 验证路由配置是否正确
- 确保没有使用`v-if`干扰
2. **数据不更新问题**
```javascript
// 使用路由参数作为key强制更新
<router-view :key="$route.fullPath"/>
```
3. **内存泄漏预防**
```javascript
deactivated() {
// 清除定时器/事件监听
clearInterval(this.timer)
window.removeEventListener('resize', this.handleResize)
}
```
## 六、与Vue3的区别
| 特性 | Vue2 | Vue3 |
| --------- | ----------------------- | ------------------------- |
| 缓存控制 | `include/exclude` | 新增`max`属性 |
| 生命周期 | `activated/deactivated` | 需要导入`onActivated`钩子 |
| 路由缓存 | 需要`keep-alive` | 内置路由组件缓存 |
| 组合式API | 不支持 | 提供`onActivated`等钩子 |

View File

@ -15,7 +15,11 @@
</div>
<div class="card-body">
<router-view />
<!-- include 包含的是组件名让不展示的路由保持挂载不被销毁 -->
<!-- <keep-alive include="Home"> -->
<keep-alive :include="['Home', 'About']">
<router-view />
</keep-alive>
</div>
</div>
</template>