前端vue3滑轮向下滑动继续发送axios请求
时间: 2023-09-16 16:11:27 浏览: 43
你可以通过监听滚动事件来实现滑轮向下滑动继续发送axios请求。以下是一个简单的示例:
```
<template>
<div ref="scrollContainer" @scroll="handleScroll">
<div v-for="item in items" :key="item.id">{{ item.title }}</div>
<div v-if="loading">Loading...</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
items: [],
page: 1,
loading: false
}
},
mounted() {
this.fetchData()
},
methods: {
fetchData() {
this.loading = true
axios.get(`https://jsonplaceholder.typicode.com/posts?_page=${this.page}&_limit=10`)
.then(response => {
this.items = this.items.concat(response.data)
this.page++
this.loading = false
})
.catch(error => {
console.log(error)
this.loading = false
})
},
handleScroll() {
const scrollContainer = this.$refs.scrollContainer
const scrollHeight = scrollContainer.scrollHeight
const scrollTop = scrollContainer.scrollTop
const clientHeight = scrollContainer.clientHeight
const remainingHeight = scrollHeight - scrollTop - clientHeight
if (remainingHeight < 100 && !this.loading) {
this.fetchData()
}
}
}
}
</script>
```
在上面的示例中,我们监听了滚动事件,并计算出滚动容器的高度、滚动位置和可见高度,以及剩余未滚动的高度。如果剩余未滚动的高度小于100且没有正在加载数据,就发送axios请求获取更多数据。每次获取数据后,我们将其添加到`items`数组中,并增加页码。如果出现错误,我们将输出错误消息。在模板中,我们使用`v-for`指令来遍历`items`数组,并在页面底部显示一个“Loading...”消息,以指示正在加载数据。