Vue switches routes and the page returns to the last cached scroll position (less code, universally effective)

need:

当切换不同路由时,期望切换后的路由页面保留上次滚动的位置。

Solutions:

利用路由中的meta属性,对不同路由页面滚动的位置做缓存,切换路由时,获取当前路由meta属性中缓存的滚动位置,再自动滚动到此位置即可。

Specific code:

router.js file

		<!-- 操作一 -->
		// 在meta属性中增加scrollTop属性
		{
    
    
        path: 'goodList',
        name: 'goodList',
        meta: {
    
    
          title: '商品列表',
          scrollTop: 0
        },
        component: resolve => require(['@/pages/goodList/index.vue'], resolve)
      },

layout.vue file

		<!-- 操作二 -->
		// 在指定内容页视图元素中,添加ref属性及mousewheel事件
        <div ref="scrollView" @mousewheel="scrollChange">
          <keep-alive>
            <router-view v-if="!needRelogin" :key="$route.fullPath" ref="pageView"></router-view>
          </keep-alive>
        </div>
        
		<!-- 操作三 -->
        // methods中定义滚动监听事件,设置路由meta属性里面的指定参数
	    scrollChange(e) {
    
    
	      console.log('父滚动条到页面顶部距离', e.target.offsetTop)
	      console.log('相对距离', this.$refs.scrollView.scrollTop)
	      console.log('绝对距离', e.target.offsetTop + this.$refs.scrollView.scrollTop)
	      // 设置路由参数scrollTop等于当前元素的相对距离
	      this.$route.meta.scrollTop = this.$refs.scrollView.scrollTop
	    }
	
		<!-- 操作四 -->
	    // monted中给元素添加滚动监听
		mounted() {
    
    
		    // 获取指定元素
		    const scrollView = this.$refs['scrollView']
		    // 添加滚动监听
		    scrollView.addEventListener('scroll', this.scrollChange, true)
		},

		<!-- 操作五 -->
		// 销毁监听
		 beforeDestroy() {
    
    
		    // 获取指定元素
		    const scrollView = this.$refs['scrollView']
		    // 移除监听
		    scrollView.removeEventListener('scroll', this.scrollChange, true)
		 },

		<!-- 操作六 -->
		// 监听路由变化时,自动滚动到上次缓存的位置
		 watch: {
    
    
		    '$route.path': {
    
    
		      handler: () => {
    
    
		        // 自动滚动到上一次缓存位置
		        this.$nextTick(() => {
    
    
		          this.$refs.scrollView.scrollTo(0, this.$route.meta?.scrollTop || 0)
		        })
		      },
		      // 深度观察监听
		      deep: true
		    }
		 },

Note: The above is all the code. The methods provided in this article can be applied to all vue projects and can solve the problem that the methods scrollBehavior and keepAlive provided by vue-router do not take effect.

Guess you like

Origin blog.csdn.net/qq_40896145/article/details/130148965