第一种方式:
<router-view v-slot="{ Component }">
<keep-alive include="Coupe,CoupeDetail">
<component :is="Component"></component>
</keep-alive>
</router-view>
第二中方式:需要在目标路由添加一个meta属性
<keep-alive>
<router-view v-if="$route.meta.KeepAlive"/>
</keep-alive>
<router-view v-if="!$route.meta.KeepAlive"/>
配置上keepAlive就可以实现状态的保存。
1.使用ref获取dom,或者使用js直接获取dom
2.keepAlive存在两个生命周期钩子,配合钩子实现代码
<div class="article_list" @scroll="scrollEvent($event)" ref="articleList"><div>
<script setup>
import { ref, toRefs,onActivated,onDeactivated,onMounted } from "vue";
const scrollTop = ref("");
const articleList = ref(null)
onActivated(() => {
console.log("子组件");
articleList.value.scrollTop = scrollTop.value;
});
onDeactivated(() => {
console.log("离开 ...");
});
function handlerScroll() {
scrollTop.value = articleList.value.scrollTop;
console.log(articleList.value.scrollTop, "778");
}
const scrollEvent = debounce(handlerScroll,500)
</script>
即可实现
如果跳转的带有是iframe,跳转回来会失效 请看下一篇文章