Vue中监听滚动事件
mounted(){
// 监听body的滚动
window.addEventListener("scroll", this.handleScroll);
}
destroyed() {
document.removeEventListener("scroll", this.handleScroll);
},
methods:{
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
console.log(scrollTop)
}
元素定义ref="scorllWrap"
mounted(){
// 监听ref为scorllWrap的滚动
this.box = this.$refs.scorllWrap
var $this = this
// 监听这个dom的scroll事件
this.box.onscroll = () => {
console.log('on scroll')
$this.handleScroll()
}
}
destroyed() {
document.removeEventListener("scroll", this.handleScroll);
},
methods:{
var scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
let box = this.$refs.scorllWrap
console.log(box.scrollTop)
}