首先,路由必须是KeepAlive模式
<script setup lang="ts">
import { onActivated } from "vue";
import { onBeforeRouteLeave } from "vue-router";
import { ref } from "vue"
const scrollRef = ref(<HTMLElement><unknown>null)
const scrollTop = ref(0)
onActivated(()=>{
console.log("恢复滚动:" , scrollTop.value);
scrollRef.value.scrollTop = scrollTop.value;
})
onBeforeRouteLeave((to, from, next)=>{
scrollTop.value = scrollRef.value.scrollTop;
next();
})
</script>
<template>
<div class="medalContainer" ref="scrollRef">
<div class="row" v-for="index in 20">
<img src="@/assets/medal.svg" />
<img src="@/assets/medal.svg" />
<img src="@/assets/medal.svg" />
<img src="@/assets/medal.svg" />
<img src="@/assets/medal.svg" />
</div>
</div>
</template>
<style scoped>
.medalContainer {
overflow-x: hidden;
overflow-y: auto;
}
</style>
标签:scrollRef,vue3,value,滚动条,vue,import,scrollTop,ref,路由
From: https://www.cnblogs.com/IWings/p/17383019.html