vue routing Jump remember scroll position, scroll back to the previous position return

Reference: https://blog.csdn.net/qq_40204835/article/details/79853685

Method 1: Use Keep-Alive and listeners

1. First, the need to introduce in the routing module

{ 
    path: ‘/scrollDemo’, 
    name: ‘scrollDemo’, 
    meta: { 
        keepAlive: true // 需要缓存 
    }, 
    component: resolve => { require([‘../view/scrollDemo.vue’],             
                                          resolve) } 
}    

2. Set the buffer assembly App.vue

<the Keep-Alive>    // cache component jump page 
   <Router-View V- IF = "$ route.meta.keepAlive" class = "ui-View" Transition-the MODE = "OUT-in"> </ add the Router- View> 
 </ the Keep-Alive>   // non-cache component jump page 
 <Router-View V- IF = "! $ route.meta.keepAlive" class = "ui-View" Transition-the MODE = "OUT-in"> </ router-view>
  

3. In the corresponding event registration page

(1) Define a scroll initial value in data

(2) In mouted, the method represents mouted been loaded in dom

window.addEventListener('scroll', this.handleScroll);

(3) .methods function for storing page

handleScroll () {
       this.scroll  = document.documentElement && document.documentElement.scrollTop
       console.log(this.scroll)
}    

4.activated is keep-alive call loads

activated() {
    if(this.scroll > 0){
        window.scrollTo(0, this.scroll);
        this.scroll = 0;
        window.addEventListener('scroll', this.handleScroll);
     }
}

Off event to prevent other problem appears when 5.deactivated pages exit

deactivated(){
     window.removeEventListener('scroll', this.handleScroll);
}

 

Method 2: Using watch and beforeRouteLeave


main.js in:

var store = new Vuex.Store({   //记得先引入vuex
    state: {
        recruitScrollY: 0
    },
    getters: {
        recruitScrollY: state => state.recruitScrollY
    },
    mutations: {
        changeRecruitScrollY(state, recruitScrollY) {
            state.recruitScrollY = recruitScrollY;
        }
    },
    actions: {

    },
    modules: {}
})

Components (/ flashSaleListX current components, namely components need to remember scrollbar position):

methods:{
      isTabRoute: function() {
            if (this.$route.path === '/flashSaleListX') {
                  let recruitScrollY = this.$store.state.recruitScrollY
                  document.documentElement.scrollTop = recruitScrollY;
            }
      }
},
watch: {
             '$route': 'isTabRoute',
},
beforeRouteLeave(to, from, next) {
      let position = document.documentElement && document.documentElement.scrollTop; //记录离开页面时的位置

      if (position == null) = 0 position
       the this . Store.commit $ ( 'changeRecruitScrollY', position) // leaving the route up deposit location 
      Next () 
}

 

Guess you like

Origin www.cnblogs.com/linjiangxian/p/11457548.html