vue3 路由页面返回时,恢复滚动条位置

首先,路由必须是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>
posted @ 2023-05-08 20:20  IWing  阅读(1026)  评论(0编辑  收藏  举报