<template>
<div class="hello" @scroll="scrollLoad" id="myScrollBox">
<h1>{{ msg }}</h1>
<ul>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
</ul>
<button @click="goForward">go 2</button>
<ul>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
<li class="my-li">aaaaaaaaa</li>
</ul>
</div>
</template> <script>
export default {
name: "HelloWorld",
data() {
return {
msg: "this is hello 1 !",
lengthToTop: 0
};
}, beforeRouteLeave(to, from, next) {
this.recordViewPortPosition();
next();
}, mounted: function() {
this.setViewPortPosition();
}, methods: {
goForward: function() {
this.$router.push("h2");
}, // 获得距离顶部的位置,暂存一个变量里
// 本方法配合recordViewPortPosition、setViewPortPosition使用
scrollLoad: function() {
let box = document.getElementById("myScrollBox");
this.lengthToTop = box.scrollTop;
}, // 离开首页时记录距离顶部的位置,存到sessionStorage里,方便回来时取用
recordViewPortPosition: function() {
sessionStorage.lengthToTop = this.lengthToTop;
}, // 离开首页再返回时,重新定位到离开时的位置
setViewPortPosition: function() {
let lengthToTop = sessionStorage.lengthToTop;
if (lengthToTop === null || lengthToTop === undefined) {
lengthToTop = 0;
}
document.getElementById("myScrollBox").scrollTop = lengthToTop; // 距离顶部100px就直接写scrollTop = 100, 不要写100+“px”
}
}
};
</script> <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
position: absolute;
width: 100%;
height: 100%;
overflow: scroll;
}
li {
display: block;
height: 100px;
width: 300px;
border: 1px solid #000;
font-size: 15px;
}
</style>
05-11 20:08