开发的时候,在A页面进行填写信息,跳转到B页面选择信息并且缓存A页面,当从B页面返回到A页面时,better-scroll卡住无法滚动,但是当我点击A页面添加图片,添加成功后,A页面恢复正常。这里我用了很多大佬的解决方案,最后我自己成功的解决方法:
mounted() {
this.initScroll();
},
methods: {
initScroll() {
this.$nextTick(() => {
//scroll为你的better-scroll创建的目标名
this.BScroll = new BScroll(this.$refs.scroll,{
click: true,
probeType: 3
});
this.pageScroll();
});
},
//保存滚动距离
pageScroll() {
let that = this;
//这里的scroll是BScroll的,直接写scroll
this.BScroll.on('scroll', (pos) => {
that.scrollY = pos.y;
})
}
},
activated () {
//让BSscroll滚动到之前存的scrollY位置
if (this.$route.meta && this.$route.meta.scrollY) {
this.BScroll.scrollTo(0, this.$route.meta.scrollY)
}
},
beforeRouteLeave (to, from, next) {
if (from.meta && (from.meta.scrollY || from.meta.scrollY === 0)) {
//将scrollY即你A页面的滚动距离存到router之中
from.meta.scrollY = this.scrollY;
next()
}
}
更新:
问题1:遇到A页面还是自动回到顶部问题
解决:可能是因为keep-alive的原因,个人暂时没懂keep-alive的原理,但是知道这个问题如何触发的。
一开始我是在app.vue里面这样写的,将整个项目全部存起来
<template>
<div id="app">
<keep-alive>
<router-view/>
</keep-alive>
</div>
</template>
然后我在A,B页面的activated ,beforeRouteLeave打个标记,在控制台查看是这样的形式,A.activated =>B.activated=>B.beforeRouteLeave=>A.activated。
因为没有触发A的beforeRouteLeave,所以this.scrollY没有存到离开时的滚动位置,导致返回A页面时自动回到了顶部。
目前我的解决办法是,修改了keep-alive,只存A页面
<template>
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
这样的话,就可以存到A页面的scrollY了。
这个办法比较无奈,当B页面需要缓存时的办法,我暂时还没找到如何处理。