mounted() { window.addEventListener('scroll', this.getScroll); }, destroyed(){ window.removeEventListener('scroll', this.getScroll); }, methods: { //監聽滾動 getScroll(){ this.indexNumTop = $("#index_num").offset().top; this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; if (!!document.documentElement.scrollTop &&document.documentElement.scrollTop >= 300){ 設置滾動大於300時的執行內容 } }
}
說明:因為監聽是針對window的,所以增加監聽后每個頁面都會監聽,只對某個頁面進行監聽的話需要在destroyed中將監聽移除