keepAlive保存滚动位置

vue2

 data() {
    return {
      scTop: 0//滚动距离顶部的位置
    }
  },
  // 进入该路由时
  activated() {
    document.documentElement.scrollTop = this.scTop
  },

  // 离开该路由前
  beforeRouteLeave(to, from, next) {
    this.scTop = document.documentElement.scrollTop || 0
    next()
  },

vue3 组合式保存位置

<script setup>
import {onActivated, ref } from "vue";
import {onBeforeRouteLeave} from 'vue-router';

const scrollTop = ref(0)
// 离开该路由前
onBeforeRouteLeave(() => {
 scrollTop.value = document.documentElement.scrollTop || 0
})

 // 进入该路由时
onActivated(() => {
  document.documentElement.scrollTop =  scrollTop.value
})
</script>

文章来源: https://taoquns.com/paper/108

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容