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)
   }
}
發佈了51 篇原創文章 · 獲贊 69 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章