vue中监控滚动事件可以直接在mounted中绑定滚动事件,然后在销毁前解绑滚动事件,例如:
<script>
export default {
mounted() {
//我这里的事例监听的是window的滚动事件
window.addEventListener('scroll', this.showbtn)
},
destroyed() {
window.removeEventListener('scroll', this.showbtn)
},
methods:{
showbtn() {
//滚动事件的代码
}
}
}
</script>
但是如果在项目中用的比较多的话,每个页面都这样写就有点不合适了。那这个时候可以把滚动事件自定义成指令
Vue.directive('scroll',{
bind(el,binding) {
let p = 0
let t = 0
let down = true
let timer = null
el.handler = () => {
p = window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop
if (t < p) {
down = true
} else {
down = false
}
t = p
let sign = 10
let scrollHeight=document.documentElement.scrollHeight//滚动条的高度
let clientHeight=document.documentElement.clientHeight//浏览器的可视高度
const scrollDistance = scrollHeight -p -clientHeight
if (scrollDistance < sign && down) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
binding.value()
}, 300)
}
}
setTimeout(() => {
window.addEventListener('scroll',el.handler)
},1000)
},
//只有绑定不解绑的话,会出现在页面加载的时候调用之前请求过的接口的情况,所以加上解绑比较好
unbind(el) {
window.removeEventListener('scroll',el.handler)
}
})