Javascript 多次触发无限滚动VueJ
我试图在我的vue chrome扩展中实现一个无限滚动。我有这段代码,但问题是当到达页面底部时,获取新数据的ajax调用被多次触发。我怎么能修理Javascript 多次触发无限滚动VueJ,javascript,ajax,vue.js,infinite-scroll,Javascript,Ajax,Vue.js,Infinite Scroll,我试图在我的vue chrome扩展中实现一个无限滚动。我有这段代码,但问题是当到达页面底部时,获取新数据的ajax调用被多次触发。我怎么能修理 mounted() { this.$store.commit('preloader', false) window.onscroll = () => { if( window.scrollY + window.innerHeight >= document.body.scrollHeight ){
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,在scroll事件到达底部但未按预期工作时将其设置为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
})
}
}
还要记住,我切换了
nextPage
属性赋值,因为我认为这样更直观(触发nextPage
方法后立即赋值给true
,结束AJAX调用后赋值给false
).是否可以为其创建JSFIDLE或codesandbox?不幸的是,我使用的数据是由我的本地开发服务器提供的,我无法在Fiddle上复制相同的结构谢谢您的帮助。我修改了if()
以添加nextPageLoaded
变量,并在我的data()
中将其设置为初始状态false。现在看来一切正常!