您的位置:首页技术文章
文章详情页

vue3利用store实现记录滚动位置的示例

浏览:13日期:2022-09-30 17:46:39
整体效果

在首页列表进行滚动浏览时进入详情页后,切换回首页时可以定位到之前浏览的位置。

vue3利用store实现记录滚动位置的示例

监听容器滚动事件

定义一个滚动事件,绑定到容器的滚动事件上,我这里做了一下节流

const savePosY = () => { if(state.timer) return; state.timer = setTimeout(() => {let node = document.querySelector('.contentWrapper');//记录滚动位置store.commit('setY',node.scrollTop)state.timer = null;clearTimeout(state.timer); },100)

在mounted中获取到容器进行绑定事件

onMounted(() => { let contentWrapper = document.querySelector('.contentWrapper'); contentWrapper.addEventListener('scroll',savePosY);})store中的配置

store中比较简单,仅包含一个state:y 以及 mutations:setY

export default { state:{ y:0 }, mutations:{setY(state,value){ state.y = value;} }}在页面跳回时获取滚动位置

同样在onMounted中操作,否则获取不到容器元素,而且由于vue中dom是异步渲染,所以我们需要在nextTick中操作才有效果

nextTick(() => { contentWrapper.scrollTop = store.state.y; })

最后

以上就是本文的全部内容啦,如果有写的不对或者有更好的方法,欢迎大家交流指出

以上就是vue3利用store实现记录滚动位置的示例的详细内容,更多关于vue 实现记录滚动位置的资料请关注好吧啦网其它相关文章!

标签: Vue
相关文章: