【问题标题】:Infinite scroll vuejs fired more than once无限滚动 vuejs 不止一次触发
【发布时间】:2020-12-05 02:56:02
【问题描述】:

我正在尝试在我的 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。任何解决方案都会受到赞赏

【问题讨论】:

  • 是否可以为相同的创建jsfiddle或codesandbox?
  • 不幸的是,我使用的数据是由我的本地开发服务器提供的,我无法在小提琴上复制相同的结构

标签: javascript ajax vue.js infinite-scroll


【解决方案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 属性分配的值,因为我认为这种方式更直观(在触发 nextPage 方法后立即分配给 true,在结束后分配给 false AJAX 调用)。

【讨论】:

  • 感谢您的帮助。我修改了if() 以添加nextPageLoaded 变量,并在我的data() 中将其设置为初始状态为false。现在似乎一切正常!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多