无限滚动vuejs触发了多次

时间:2020-08-15 12:23:18

标签: 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 ){
        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。任何解决方案都会得到赞赏

1 个答案:

答案 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调用后。

相关问题