以下内容deepSeek生成未测试过
1. 配置路由和组件
// router.js
const routes = [
{
path: '/list',
component: ListPage
},
{
path: '/add',
component: AddPage,
meta: { requiresAuth: true }
},
{
path: '/edit/:id',
component: EditPage,
meta: { requiresAuth: true }
}
]
2. 配置带缓存的视图容器
<!-- App.vue -->
<template>
<div id="app">
<keep-alive :include="cachedViews">
<router-view></router-view>
</keep-alive>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['cachedViews'])
}
}
</script>
3. 配置状态管理(Vuex)
// store.js
export default new Vuex.Store({
state: {
cachedViews: []
},
mutations: {
ADD_CACHED_VIEW: (state, viewName) => {
if (!state.cachedViews.includes(viewName)) {
state.cachedViews.push(viewName)
}
},
REMOVE_CACHED_VIEW: (state, viewName) => {
const index = state.cachedViews.indexOf(viewName)
if (index > -1) {
state.cachedViews.splice(index, 1)
}
}
}
})
4. 配置导航守卫
// router.js
router.beforeEach((to, from, next) => {
// 从列表进入新增页时清除缓存
if (from.path === '/list' && to.path === '/add') {
store.commit('REMOVE_CACHED_VIEW', 'AddPage')
}
// 从新增页进入编辑页时添加缓存
if (from.path === '/add' && to.path.startsWith('/edit/')) {
store.commit('ADD_CACHED_VIEW', 'AddPage')
}
next()
})
5. 配置组件名称(关键步骤)
<!-- AddPage.vue -->
<script>
export default {
name: 'AddPage', // 必须与缓存名称一致
data() {
return {
formData: {} // 你的表单数据
}
}
}
</script>
6. 处理编辑页返回逻辑
<!-- EditPage.vue -->
<script>
export default {
methods: {
handleSave() {
// 保存成功后返回新增页
this.$router.push('/add')
}
}
}
</script>
实现效果说明:
-
从列表页进入新增页:
/list
→/add
-
清除缓存,每次都是全新实例
-
表单内容为空
-
-
从新增页进入编辑页:
/add
→/edit/123
-
添加新增页缓存
-
保留当前表单内容
-
-
从编辑页返回新增页:
/edit/123
→/add
-
使用缓存实例
-
保持跳转前的表单内容
-
-
再次从列表页进入新增页:
/list
→/add
-
再次清除缓存
-
显示全新空白表单
-
注意事项:
-
组件
name
属性必须与缓存名称完全一致 -
使用Vuex管理缓存列表以保证状态持久化
-
对于复杂场景可结合
<keep-alive>
的exclude
属性 -
必要时可在
activated
生命周期重置部分数据
这种方案通过动态管理缓存列表,实现了细粒度的页面缓存控制,既保证了用户体验的连贯性,又满足了不同场景下的缓存需求。