我正在尝试在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。任何解决方案都会得到赞赏
答案 0 :(得分:1)
也许这是一个错字,但我看不到您实际上是在nextPageLoaded
语句中使用if
属性作为标志。
应该是类似
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
属性分配的值,因为我认为这种方式更直观(触发true
方法后立即分配给nextPage
,将其分配给false
结束AJAX调用后。