Optimization_Channel-Scroll bar position

None of the following effects occurred routing switching! ! !

 Knowledge Supplement:

  activated: Called when the component is activated, it will also be called when the component is rendered for the first time , and then it will be called every time keep-alive is activated.

  deactivated: Called when the component is deactivated.

keep-alive Note: These two life cycles will only be called when the    component is  wrapped. If it is used as a normal component, it will not be called. After 2.1.0 the version is used and  exclude excluded, even if it is wrapped in  keep-alive , these two hooks are still will not be called! In addition, this hook will not be called when rendering on the server side.

Here our page home component is  keep-alive wrapped

Target

  • clear data structure
  • Tabs switch to save the current position
  • After the tabs are switched, set the position

step

1. Clarify the data structure and define variables in Home/index.vue

// Correspondence between "channel name" and "scroll bar position", format { 'recommended ID': 211, 'htmlID': 30, 'developer information ID': 890 }
 data () {
    return {
      // 当前频道的ID
      channelId: 0,
      channelScrollTObj: {} //频道名称”和“滚动条位置”之间的对应关系
    }
  }

2. Bind the scroll event to the window (the effect here shows that the scroll bar is the entire document file) ------ here you can add a binding event in the activated () or created () life cycle function, because the home component is the first Both activated() and created() will be executed for the second creation, and the tab switching effect here will not cause deactivated() and destroyed() of the home component to occur! That is to say, the home data will not be set to the initial state!

activated () {
    // 原生js通过window.onscroll监听
    window.addEventListener('scroll', this.scrollFn) // 监听滚动事件
  },
methods:{
     scrollFn () {
      // 保存各个频道滚动的位置
      this.channelScrollTObj[this. channelId] = document.documentElement.scrollTop
      console.log(this.channelScrollTObj)
    }
}

3. Bind the change event to the tabs tag (after switching!!)

 <van-tabs
      v-model="active"
      animated
      swipeable
      class="channel-tabs"
      @change="channelChangeFn"
    >
methods:{
     channelChangeFn () {
      // 当频道发生切换时,将原先保存的滚动记录还原出来
      document.documentElement.scrollTop = this.channelScrollTObj[this. channelId]
    }
}

4. Background printing: 

5. Finally --- Bind events to the global dom (here is window, all components share a window) must remember to destroy

 deactivated () {
    // 给全局dom绑定事件(这里是window,所有的组件共用一个window)一定要记得在摧毁
    window.removeEventListener('scroll', this.scrollFn)
  }

 

Guess you like

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