1、方法一

在点击的时候记录滚动条位置,存入本地
再次进入该路由读取滚动跳位置

1、1 跳转时路由存入scroll

  • 如果要有多个页面,可以把名称也存进去,这里默认一个页面
    methods: {
      go() {
        console.log(document.documentElement.scrollTop)
        localStorage.setItem("scroll", document.documentElement.scrollTop)
        this.$router.push({path: '/'})
      }
    }
复制代码

1、2 读取scroll位置

  • 再次进入该路由时从本地录取scroll位置

利用scrollBehavior ,在router/index.js中,配置路由中的scrollBehaviors事件

const router = new VueRouter({
  mode: 'hash',
  routes,
  scrollBehavior(to, from){
    if(to.name==='fatherSlot'){ //name为路由名字
      return {x:0, y: parseInt(localStorage.getItem('scroll'))}//读取本地的scroll
    }
    console.log("to",to,"from",from)
  }
})
复制代码

2、方法二

利用vuekeep-alive , 使用缓存机制来记录滚动条位置
但是有个缺点,页面刷新后就不记录了,但是简单高效

2、1 配置需要缓存的路由

  • 缓存pageA,pageB,里面代码都一样,如演示图一样。pageA,pageC为组件的名字.

html

    <keep-alive :include="['pageA','pageC']">
      <router-view/>
    </keep-alive>
复制代码

2、2 在路由内记录滚动位置

javascript

    data() {
      return {
        curScrollTop: 0 //记录滚动条位置对象
      }
    },
    //此钩子函数会反复触发,是keep-alive特有的钩子函数,取
    activated() {
      document.documentElement.scrollTop = this.curScrollTop || 0
    },
    //路由离开时的钩子函数,存
    beforeRouteLeave (to, from, next) {
      this.curScrollTop = document.documentElement.scrollTop || 0
      next()
    },
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。