VUE项目添加全局滚动条记录功能

思路:
在离开某个路由时 保存当前页面的滚动条高度 再次访问时将滚动条高度重新赋值

方式1:
尝试使用VueRouter的scrollBehavior()方法

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
})

调试时发现 在进入无滚动条页面返回有记录值的有滚动条页面时会出现问题。且该方法执行在页面渲染之前,弃用换其他方法。

方式2:
全局混入activated生命周期

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或其他根组件

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

猜你喜欢

转载自blog.csdn.net/Beatingworldline/article/details/128219107