VUE project adds global scroll bar recording function

Idea:
Save the scroll bar height of the current page when leaving a route and reassign the scroll bar height when visiting again

Method 1:
Try to use VueRouter's scrollBehavior() method

const createRouter = () => new Router({
    
    
  scrollBehavior (to, from, savedPosition) {
    
    
    let val = store.state.moreDetails.scrollTopObj[to.path]
    return val?{
    
    x:0, y: parseInt(val)}:{
    
     y: 0 } //在有滚动条和无滚动条页面间切换时会出问题
  },
  routes: constantRoutes
})

When debugging, it is found that there will be problems when entering a page without a scroll bar and returning a page with a scroll bar with a recorded value. And this method is executed before the page is rendered, deprecated and replaced with other methods.

Method 2:
Globally mixed into the activated lifecycle

VueX:

const state = {
    
    
    scrollTopObj:{
    
    },
}

const mutations = {
    
    
  SET_SCROLLTOPOBJ: (state, obj) => {
    
    
    state.scrollTopObj[obj.key] = obj.val
  },
}

Main.js

import store from './store'

Vue.mixin({
    
    
  // created: function () {
    
    
  //     console.log('全局混入')
  // },
  activated(){
    
    
    document.documentElement.scrollTop = this.$store.state.moreDetails.scrollTopObj[this.$route.path]
  },
})

APP.vue or other root components

  watch: {
    
     
    '$route.path':{
    
    
      handler: function(newVal,oldVal) {
    
    
        this.$store.commit('SET_SCROLLTOPOBJ',{
    
    key:oldVal,val:document.documentElement.scrollTop})
      },
    },
  },

Guess you like

Origin blog.csdn.net/Beatingworldline/article/details/128219107