最近作项目时遇到一个问题,产品搜索后出来相关的列表,点击相关商品进入它的详情,返回后组件被从新建立,但产品需求是须要保留进入详情是列表的位置的。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