vue3+router+setup如何实现页面状态保存

发布时间:2024年01月18日

vue3的keep-alive和vue2很大不同,折腾很久。

?App.vue代码

<script setup>
    import {ref,watch} from 'vue'
	import {useRouter } from 'vue-router';
    const include = ref([])
	const router = useRouter()
	var from = ref(null)
    watch(//这里和vue2有点区别
	  () => router.currentRoute.value,
	  (to) => {
	    console.log('to',to)
		if (to.meta && to.meta.keepAlive) {
			!include.value.includes(to.name) && include.value.push(to.name);
		}
		if (from.value && from.value.meta.keepAlive && to.meta.deepth < from.value.meta.deepth) {
			var index = include.value.indexOf(from.value.name);
			index !== -1 && include.value.splice(index, 1);
		}
		from.value = to
	  }
	)
</script>

<template>
	<div id="app">
		<router-view v-slot="{ Component, route  }">
			<keep-alive :include="include">
				<component :is="Component" :key="route.name" v-if="route.meta.keepAlive"></component>
			</keep-alive>
			<component :is="Component" :key="route.name" v-if="!route.meta.keepAlive" />
		</router-view>
	</div>
</template>

路由文件index.js

    {
		path:'/list',
		name:'list',
		component:listPage,
		meta: {
			keepAlive: true,
			deepth:1
		},
	},
	{
		path:'/detail',
		name:'detail',
		component:Detail,
		meta: {
			keepAlive: true,
			deepth:2
		},
	},
    {
		path:'/edit',
		name:'edit',
		component:edit,
		meta: {
			keepAlive: true,
			deepth:3
		},
	},

具体页面ListPage.vue

安装一个插件npm install vite-plugin-vue-setup-extend --save,为了能在setup上定义组件名name

<script setup name='list'>

</script>

文章来源:https://blog.csdn.net/qq_31164261/article/details/135676621
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。