首先在 mounted中写入:
mounted() {
window.addEventListener("scroll", this.handleScroll, true);
},
methods中写入:
methods:{
handleScroll() {
let scrolltop =document.documentElement.scrolltop || document.body.scrollTop;
scrolltop > 30 ? (this.gotop = true) : (this.gotop = false);
},
toTop() {
let top = document.documentElement.scrollTop || document.body.scrollTop;
const timeTop = setInterval(() => {
document.body.scrollTop = document.documentElement.scrollTop = top -= 50;
if (top <= 0) {
clearInterval(timeTop);
}
}, 10);
}
}
其中toTop是点击事件的名称,即可完成返回顶部。