簡體   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