Optimization_Home page-scroll bar position

Target:

  • Switch between home page and my page

  • Home page scroll bar position needs to be restored

 

 

 keep-alive will not cache the position of the scroll bar! !

1. Routing object /home, add meta additional information

Knowledge point: The component is cached, and if it is cut away, it will lose its activation. The life cycle method triggers deactivated

          None is cached, cut away, destroyed destroys the life cycle method trigger

  Because the home component is cached by keep-alive, when the page is switched out, only html and css js will be saved, and the scroll position will not be saved

  Reason: switch to my page, the page height is not enough, there is no scroll bar (this scroll bar is for the entire webpage), the scroll position will return to the top, so switch to the home page, the scroll bar is still at the top

  Solution: The home page is out of focus (when switched), save the scroll position in his routing object meta

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

 2. Bind the scroll event to the 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
    },
}

Guess you like

Origin blog.csdn.net/m0_65812066/article/details/128633936