vue跳转页面返回后定位问题

本文介绍如何在Vue应用中使用ref、Vuex来监听并保存滚动元素的位置,实现页面返回时滚动条回到之前的位置。包括:1. 给滚动元素添加ref标记;2. 监听滚动事件;3. Vuex保存滚动位置;4. 返回时恢复滚动位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、给滚动元素添加ref标记

   <div ref="wrapper" }"><div>

2、监听滚动事件

  mounted() {
    this.$refs.wrapper.addEventListener('scroll', this.handelscroll)
  },

3、vuex保存元素滚动的位置scrollTop

export default new Vuex.Store({
  state: {
    scrollTop: 0,
  },
  mutations: {
    handleScroll(state, value) {
      state.scrollTop = value
    },
  },
  getters: {},
})
    handelscroll() {
      let scrollTop = this.$refs.wrapper.scrollTop
      this.$store.commit('handleScroll', scrollTop)
    },

4、返回时给滚动元素到指定位置

  activated() {
    this.$refs.wrapper.scrollTop = this.$store.state.scrollTop
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值