在若依框架中,当使用标签页(Tab)切换时,默认行为会导致页面重新加载,从而引发以下问题: 1. 表单数据丢失 2. 页面状态重置 3. 不必要的网络请求重复发送
<template>
<keep-alive :include="cachedViews">
<router-view :key="key" />
</keep-alive>
</template>
<script>
export default {
computed: {
cachedViews() {
return this.$store.state.tagsView.cachedViews
},
key() {
return this.$route.path
}
}
}
</script>
src/store/modules/tagsView.js
中修改:const state = {
visitedViews: [],
cachedViews: []
}
const mutations = {
ADD_CACHED_VIEW: (state, view) => {
if (state.cachedViews.includes(view.name)) return
if (!view.meta.noCache) {
state.cachedViews.push(view.name)
}
},
// 其他相关mutations...
}
确保路由配置中设置了正确的meta
属性:
{
path: 'your-path',
component: YourComponent,
name: 'YourComponentName',
meta: {
title: '页面标题',
noCache: false // 设置为false表示需要缓存
}
}
对于复杂页面,可以手动保存状态:
// 在页面组件中
data() {
return {
formData: {},
// 其他状态数据
}
},
beforeRouteLeave(to, from, next) {
// 离开前保存状态
this.$store.dispatch('tagsView/savePageState', {
path: this.$route.path,
state: {
formData: this.formData
// 其他需要保存的状态
}
})
next()
},
activated() {
// 返回页面时恢复状态
const savedState = this.$store.state.tagsView.savedStates[this.$route.path]
if (savedState) {
this.formData = savedState.formData
// 恢复其他状态
}
}
meta: { noCache: true }
keep-alive
配合路由缓存即可deactivated
钩子)清理定时器等资源通过以上方法,可以有效解决若依框架中标签页切换导致的数据丢失问题,提升用户体验。