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

本文介绍了Vue3中使用`keep-alive`组件与Vue2的不同之处,特别是在路由守卫中的`meta`属性处理,以及如何通过`vite-plugin-vue-setup-extend`插件在`setup`中设置组件名称。
摘要由CSDN通过智能技术生成

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值