最近作項目時遇到一個問題,產品搜索後出來相關的列表,點擊相關商品進入它的詳情,返回後組件被從新建立,但產品需求是須要保留進入詳情是列表的位置的。vue
首先有三個頁面(首頁,搜索列表頁,詳情頁),從首頁到搜索列表頁是不須要保存組件的,從詳情頁到搜索列表頁是須要記錄列表位置的。vue-router
首頁: this
1.先保持搜索列表頁組件狀態不刷新spa
//進入搜索頁面時
beforeRouteEnter(to, from, next) {
console.log(to,from);
if (from.path == '/') {
console.log("/");
next(vm => {
vm.seachlist=[]; //清空搜索列表
vm.keyword=""; //清空關鍵字
});
}
},
複製代碼
3.從詳情頁進入搜索列表頁時,列表存在,但列表位置不在離開的位置,因此咱們須要在離開時記錄離開時滾動的位置,並將列表滾動到相應的位置。3d
記錄位置:code
//初始化better-scroll
initbetterscore:function () {
this.scroll = new Bscroll(this.$refs.mescroll, {
scrollY:true,
pullUpLoad:true,
click:true,
})
this.scroll.on('pullingUp',()=>{
this.getseachlist();
})
//監聽scroll的滾動,獲取它滾動的高度
this.scroll.on('scroll',(obj)=>{
this.scrollTop=obj.y;
})
},
複製代碼
設置位置:router
//進入該頁面時
beforeRouteEnter(to, from, next) {
console.log(to,from);
if (from.path == '/') {
console.log("/");
next(vm => {
vm.seachlist=[];
vm.keyword="";
});
} else {
next(vm => {
vm.scroll.scrollTo(0,vm.scrollTop);
vm.scroll.refresh(); //從新計算 better-scroll,當 DOM 結構發生變化的時候務必要調用確保滾動的效果正常
})
}
},
複製代碼
效果圖:cdn
以上就是本身的決解方法,歡迎留言指教哦!blog