[英]Infinite scroll vuejs fired more than once
我正在嘗試在我的 vue chrome 擴展中實現無限滾動。 我有這段代碼,但問題是當到達頁面底部時,多次調用 ajax 來獲取新數據。 我該如何解決?
mounted() {
this.$store.commit('preloader', false)
window.onscroll = () => {
if( window.scrollY + window.innerHeight >= document.body.scrollHeight ){
console.log('fired')
this.nextPageLoaded = false
this.nextPage()
}
}
},
methods: {
nextPage() {
console.log('Loading next page')
axios.get('https://localhost:8080/api/media')
.then( (response) => {
console.log(response.data)
this.$store.commit('profileMedia', response.data.media)
this.nextPageLoaded = true
})
}
}
我嘗試在加載數據后將變量nextPageLoad
設置為 true,當滾動事件到達底部但無法按預期工作時設置為 false。 任何解決方案將不勝感激
也許這是一個錯字,但我沒有看到您實際上在if
語句中使用nextPageLoaded
屬性作為標志。
它應該是這樣的
mounted() {
this.$store.commit('preloader', false)
window.onscroll = () => {
if ( (window.scrollY + window.innerHeight >= document.body.scrollHeight)
&& !this.nextPageLoaded) {
console.log('fired')
this.nextPageLoaded = true
this.nextPage()
}
}
},
methods: {
nextPage() {
console.log('Loading next page')
axios.get('https://localhost:8080/api/media')
.then( (response) => {
console.log(response.data)
this.$store.commit('profileMedia', response.data.media)
this.nextPageLoaded = false
})
}
}
另外請記住,我切換了nextPageLoaded
屬性分配的值,因為我認為這種方式更直觀(在觸發nextPage
方法后立即分配為true
,在結束 AJAX 調用后分配為false
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.