#思路:
路由跳转之前(或是Tab切换之前),记录一个高度值Value。之后,控制其滚动scrollTo(0, value)
,即可。
#知识点
- keep-alive,router-view组件缓存,不重新加载。
- activated钩子函数,当keep-alive缓存组件被切换,它的 activated 钩子函数将会被对应执行。
- this.$nextTick(),等到DOM更新完成之后,然后,执行this.$nextTick,类似于Promise then()。此处,可以防止“Tab切换”时,无法滚动到底部的问题。
#代码
- 场景1:路由切换时,记录滚动高度
<template>
<div>
<div class="about-content" ref="about"></div>
</div>
</template>
<script>
export default {
data() {
return {
scrollHeight: 0, // 记录滚动高度
};
},
mounted() {
this.aboutUs();
},
activated(){
// 等到DOM更新完成之后,然后,执行this.$nextTick,类似于Promise then()
this.$nextTick(() => {
this.$refs.about.scrollTo(0, this.scrollHeight);
})
},
beforeRouteLeave(to, from, next) {
this.scrollHeight = this.$refs.about.scrollTop;
next();
},
};
</script>
<style scoped>
.about-content{
padding: 10px; background: #fff;
overflow: auto;
height: calc(100vh - 1.2rem);
-webkit-overflow-scrolling: touch;
}
</style>
- 场景2:tab切换时,记录滚动高度
<template>
<div>
<nav>
<div :class="{'nav-item':true, 'active':isShow}" @click="navClickToggle(1)">盒子1</div>
<div :class="{'nav-item':true, 'active':!isShow}" @click="navClickToggle(2)">盒子2</div>
</nav>
<main class="main" ref="main">
<!-- 盒子1 -->
<section v-show="isShow"> </section>
<!-- 盒子2 -->
<section v-show="!isShow"></section>
</main>
</div>
</template>
<script>
export default {
name: "Start",
data() {
return {
isShow: true,
mainScrollHeight:"",
currentScrollHeight:0,
willScrollHeight:0,
}
},
activated: function () {
// 记录滚动位置
this.$refs.main.scrollTo(0,this.mainScrollHeight)
},
beforeRouteLeave(to, from, next) {
this.mainScrollHeight = this.$refs.main.scrollTop;
next();
},
methods: {
/**
* 导航栏点击切换,于此同时,记录滚动位置
* @param flag 1子盒子 2子盒子
*/
navClickToggle(flag) {
this.isShow = !this.isShow;
this.mainScrollHeight = this.$refs.main.scrollTop;
if(flag === 1){
this.$nextTick(function(){
this.currentScrollHeight = this.mainScrollHeight;
this.$refs.main.scrollTo(0,this.willScrollHeight)
})
}else if(flag === 2){
this.$nextTick(function(){
this.willScrollHeight = this.mainScrollHeight;
this.$refs.main.scrollTo(0,this.currentScrollHeight);
})
}
},
},
}
</script>
<style lang="scss" scoped>
.main {
height: calc(100vh - 2.4rem);
height: -moz-calc(100vh - 2.4rem);
height: -webkit-calc(100vh - 2.4rem);
overflow: auto;
&::-webkit-scrollbar {
width: 0;
height: 0;
}
}
</style>
网友评论