vue 項目返回上一頁,滾動到離開時的位置,網上能找到不少方法,以下嘗試一種。
例如,首頁有個列表,點擊列表進入二級頁面,返回的時候保持在原位置。首先在首頁的視圖外套上 keep-alive , include 表示只針對 name = 'Home' 的組件進行緩存
<keep-alive include='Home'> <router-view/> </keep-alive>
然后,在首頁的 Home 組件內,使用 beforeRouteLeave ,組件內的路由導航守衛,路由離開前,獲取滾動高度,並記錄在 data 中,當再次進入首頁,判斷是否存在這個滾動高度,若存在,則設置高度,否則置為 0
data:{ homeTop : 0, }, activated(){ // do something console.log('activated home') document.getElementById('app').scrollTop = this.homeTop || 0 }, beforeRouteLeave (to, from, next) { // console.log('leave') let app = document.getElementById('app') this.homeTop = app.scrollTop || 0 next() },
end
