繁体   English   中英

无限滚动 vuejs 不止一次触发

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM