vue开发SPA中,路由切换时,子组件间滚动行为相互影响的解决办法

现在有A、B两个路由组件,均注册在同一路由下,通过<router-link></router-link>切换路由配合<router-view></router-view>进行页面切换。

<template>
  <div class="container">
	<router-link :to="{ name: 'A' }">A</router-link>
	<router-link :to="{ name: 'B'}">B</router-link>
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
  </div>
</template>

但是当在A组件中滚动到页面底部时,再通过<router-link>B</router-link>到B组件,会出现B组件也直接渲染为页面底部,而不是页面头部。

解决方法
首先更改router.js文件。

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  routes: [
    {
	   	path: '/', 
	   	redirect: '/A', 
	   	name: 'index', 
	   	component: () => import('./views/index.vue'), 
	   	children: [
	      { 
	      	path: '/A',
	      	name:'A',
	      	component: () => import('./views/B.vue'), 
	      	meta: {x: 0, y: 0}
	      }, {
	      	path: '/B',
	      	name:'B',
	      	component: () => import('./views/B.vue'), 
	      	meta: {x: 0, y: 0}
	      },
	   	]
    },
  scrollBehavior (to, from, savedPosition) {
    return to.meta
  }
})

然后在首页index组件中,记录滚动的位置保存到路由meta中。

mounted() {
  window.onscroll = () => {
  	this.$route.meta.y = window.pageYOffset
  }
},

下面是节流写法:

mounted() {
  window.onscroll = this.justifyPos
},
methods: {
  justifyPos() {
    if (this.timerId) {
      clearTimeout(this.timerId)
    }
    this.timerId = setTimeout(() => {
      this.$route.meta.y = window.pageYOffset
    }, 300)
   }
}
发布了59 篇原创文章 · 获赞 78 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/PrisonersDilemma/article/details/103046187