1、app.vue使用keep-alive组件,vue3中最新写法,keep-alive嵌套要放在router-view里面,这样就导致清除缓存存在问题,通过v-if控制时,路由会先刷新再跳转,这样就导致跳转加载闪屏,用户体验不好

<router-view v-slot="{ Component }" v-if="isRouterAlive">
	<keep-alive>
		<component :is="Component" v-if="$route.meta.keepAlive" :key="$route.name" />
	</keep-alive>
    <component :is="Component" v-if="$route.meta.keepAlive"
							:key="$route.name" />
</router-view>

2、router.js配置路由,添加拦截

{
	path: '/student',
	name: 'student',
	component: () => import('../components/student.vue'),
	meta: {
		keepAlive: true,
		cacheList: ['studentDetail', 'evaluate']
	}
},
//路由拦截
router.beforeEach((to, from, next) => {
	//从cacheList中的任何一个页面返回,当前页面缓存
	const cacheList = to.meta.cacheList
	if (cacheList) {
		if (cacheList.indexOf(from.name) > -1) {
			to.meta.keepAlive = true
		} else {
			//如果没有纳进cacheList缓存需求,就不缓存
			if (from.name) {
				to.meta.keepAlive = false
			}
			// 导航跳转需要缓存处理
			if (from.meta.cacheList) {
				to.meta.keepAlive = true
			}
		}
	}
	next()
})

3、搭配activated和onBeforeRouteLeave路由离开时状态,处理同样需要缓存页面的刷新问题

    var refreshFlag = ref(0)
	onActivated(() => {
		if (refreshFlag.value == 1) {
			currentPage.value = 1
			pageSize.value = 10
			params.page = currentPage.value
			params.limit = pageSize.value
			getList()
		}
	})
    // 跳转导航去掉缓存,分B页面需要缓存和不需要缓存两种情况
	onBeforeRouteLeave((to, from, next) => {
		if (to.meta.cacheList && to.meta.cacheList.length > 0 || !to.name) {
			refreshFlag.value = 1
		} else {
			refreshFlag.value = 0
		}
		next()
	})

再跳转回来后刷新表格。

Logo

前往低代码交流专区

更多推荐