問題: 在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) })