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()
	})

再跳转回来后刷新表格。

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐