我正在Nuxt 2中实现无限滚动。当我滚动到页面底部时,我的函数执行了两次(两个GET
请求)。应该一次。如何实现呢?
<template>
<main>
<div v-for="content in contents" :key="content.id">
<div>{content.name}</div>
</div>
</main>
</template>
<script>
// Minimal setup
import { throttle } from 'lodash'
import axios from 'axios'
data() {
return {
loading: false,
contents: []
}
},
// Methods
methods: {
handleScroll() {
// Vanilla JS
const pixelsFromWindowBottomToBottom = 0 + document.body.offsetHeight - window.pageYOffset - window.innerHeight
if (pixelsFromWindowBottomToBottom < 200) {
this.getContents() // <-- Fires twice. Why?
}
},
getContents() {
this.loading = true // Got it. This is this issue
axios.get('foo')
.then(({ data }) => {
this.contents = this.contents.concat(data) // array
})
}
},
created() {
if (process.browser) {
document.addEventListener('scroll', throttle(this.handleScroll, 300))
}
}
</script>
this.getContents()
似乎触发/渲染两次:我在页面上显示重复的数据。我将document.addEventListener
放在正确的位置了吗?
更新:
this.loading = true
引起了它。当我更新data()
时,这会触发两次执行。