vue3.0记录滚动位置的两种方法
第一种方法onActivated+onBeforeRouteLeave 方法实现import { onBeforeRouteLeave} from 'vue-router'const scrollRef = ref(null)const scrollTop = ref(0)onActivated(()=>{nextTick(()=>{scrollRef.value.scrollTop
·
第一种方法
onActivated + onBeforeRouteLeave 方法实现
1.思路
- 页面首先要是缓存的组件实例 keep-alive
- 用onActivated 才能将滚动位置 缓存起来
- 每次进入都要将存储的位置重新赋值给页面
- 路由守卫 beforeRouteLeave路由离开前记录当前的位置
import { onBeforeRouteLeave} from 'vue-router'
const scrollRef = ref(null)
const scrollTop = ref(0)
onActivated(()=>{
nextTick(()=>{
scrollRef.value.scrollTop = scrollTop .value
})
})
onBeforeRouteLeave((to, from, next)=>{
scrollTop .value = scrollRef.value.scrollTop
next()
})
<div class="mall-page" ref="scrollRef" >
......
<div>
.mall-page{
background: #FFFFFF;
overflow: auto;
height: 100vh;
}
第二种
事件监听 + vuex存储或者本地存储都行
1.思路
- 监听页面最外层div滚动事件,将当前的位置存储起来
- 不断滚动,不断记录需要对函数限制执行频率
- 销毁时需移除监听
import { debounce } from 'throttle-debounce' //限制函数的执行频率
import { ref, onActivated, nextTick, onMounted, onUnmounted } from 'vue'
const scrollRef = ref(null)
onActivated(()=>{
nextTick(()=>{
scrollRef.value.scrollTop = localStorage.getItem("scrollTop")
})
})
onMounted(()=>{
scrollRef.value.addEventListener('scroll', handle_Scroll.bind(this))
})
onUnmounted(()=>{
scrollRef.value.removeEventListener('scroll', handle_Scroll.bind(this))
})
const handle_Scroll = debounce(100, function (e) {
localStorage.setItem("scrollTop",scrollRef.value.scrollTop)
})
<div class="mall-page" ref="scrollRef" >
......
<div>
.mall-page{
background: #FFFFFF;
overflow: auto;
height: 100vh; // 一定要设置高度才会滚动
}
更多推荐
已为社区贡献5条内容
所有评论(0)