优化_首页-滚动条位置

目标:

  • 切换首页和我的页面

  • 首页滚动条位置需要恢复

 

 keep-alive不会缓存滚动条的位置的!!

1.路由对象/home,上添加meta额外的信息

知识点:组件被缓存,切走了就会失去激活生命周期方法触发 deactivated

          无被缓存,切走了,destroyed摧毁生命周期方法触发

  因为home组件被keep-alive缓存,当切换出去了该页面只会被保存html和css js,而不会保存滚动位置

  原因:切换到我的页面,页面高度不够,没有滚动条(此滚动条为整个网页的),滚动位置会回到顶部,所以切换到首页,,滚动条还在顶部

  解决:首页失焦(被切换时),在他的路由对象meta中保存滚动位置

 {
        path: 'home',
        name: 'home',
        component: () => import(/* webpackChunkName:"home" */'@/views/home'),
        meta: { scrollT: 0 }
      }

 2.给window绑定滚动事件

 activated () {
    // 原生js通过window.onscroll监听
    window.addEventListener('scroll', this.scrollFn) // 监听滚动事件

    // 当从我的切换到首页时(激活时),将滚动条复位
    document.documentElement.scrollTop = this.$route.meta.scrollT
  },
  deactivated () {
    console.log(this.$route)
    // 给全局dom绑定事件(这里是window,所有的组件共用一个window)一定要记得在摧毁
    window.removeEventListener('scroll', this.scrollFn)
  }
methods:{
    scrollFn () {
      // 每个页面都有自己的路由规则
      this.$route.meta.scrollT = document.documentElement.scrollTop
    },
}

猜你喜欢

转载自blog.csdn.net/m0_65812066/article/details/128633936