问题: 在mounted里面直接添加监听这样监听到的值一直是0
window.addEventListener('scroll', this.handleScroll);
解决办法:添加一个参数 true
window.addEventListener('scroll', this.handleScroll, true);
最后别忘记在离开的时候移除监听
destroyed () {
window.removeEventListener('scroll', this.handleScroll);
}
移除监听也可以在mounted里面写,通过hook监听组件销毁钩子函数,并取消监听事件,增加代码的可读性
this.$once('hook:beforeDestroy', () => { window.removeEventListener('scroll', this.handleScroll) })