vue 跳转其他页面再跳回原页面记录滚动的位置
此方法使用当页面存在滚动条,当跳转其他页面,再跳转到此页面时,保存当前的位置;
前提 必须给组件设置 keep-alive
<div class="shop-list" ref="shopList" >
<div class="page_swiper">
<van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
<van-swipe-item>
<a href="">1</a>
</van-swipe-item>
<van-swipe-item>
<a href="">2</a>
</van-swipe-item>
<van-swipe-item>
<a href="">3</a>
</van-swipe-item>
<van-swipe-item>
<a href="">4</a>
</van-swipe-item>
</van-swipe>
</div>
<!-- 封装提取部分 商品 -->
<tabShopList :searchKey="searchKey" :isTabFixed="isTabFixed"></tabShopList>
</div>
注意 shopList 是有滚动效果的
beforeRouteLeave (to, from, next) {
// 记录 滚动的高度 this.$refs.shopList.scrollTop 其中shopList 是滚动的元素
sessionStorage.shopAskPositon= this.$refs.shopList.scrollTop
next();
},
beforeRouteEnter (to, from, next) {
console.log(from)
if (!sessionStorage.shopAskPositon|| from.name !== 'tradeDetail') {
//当前页面刷新不需要切换位置 或者通过form来判断
sessionStorage.shopAskPositon= 0;
// 下面可以操作此页面中data的值和方法
next(vm => {
vm.isTabFixed = false
});
} else {
next(vm => {
if (vm && vm.$refs.shopList) {
//通过vm实例访问this
setTimeout(function() {
vm.$refs.shopList.scrollTo(0, sessionStorage.shopAskPositon, false);
}, 0); //同步转异步操作
}
});
}
},
注意观察滚动切换页面后 保存的高度值是否有变化
其他效果看个人情况而定,不懂的可以留言