참고한 코드
끝에 도달여부를 담는 변수
data: () => ({
reachBottom: false,
}),
스크롤이 끝에 도달했는지 계산하는 함수
bottomVisible() {
const { clientHeight, scrollHeight } = document.documentElement;
const bottomOfPage = clientHeight + window.scrollY >= scrollHeight;
return bottomOfPage || scrollHeight < clientHeight;
},
현 window에 함수를 적용시키기
created() {
window.addEventListener("scroll", () => {
this.reachBottom = this.bottomVisible();
});
},
reachBottom의 값을 지켜 보기
watch: {
reachBottom(bottom) {
if (bottom) this.addData(); // 데이터 추가하기
},
},
<template>
<v-container>
<div v-for="(book, i) in bookList" :key="i">
<v-card>
<v-list-item-title class="headline mb-1">
{{ book }}
</v-list-item-title>
</v-card>
</div>
</v-container>
</template>
<script>
export default {
data: () => ({
bookList: [],
startIdx: 0,
reachBottom: false,
}),
created() {
window.addEventListener("scroll", () => {
this.reachBottom = this.bottomVisible();
});
this.addBooks();
},
methods: {
bottomVisible() {
const { clientHeight, scrollHeight } = document.documentElement;
const bottomOfPage = clientHeight + window.scrollY + 100 >= scrollHeight;
return bottomOfPage || scrollHeight < clientHeight;
},
addBooks() {
// 일단 무한 스크롤 방지
if (this.bookList.length > 20) return;
this.bookList = [...this.bookList, ...[1,2,3,4,5]];
// if(this.bottomVisible())
// this.addBooks();
},
},
watch: {
reachBottom(bottom) {
if (bottom) this.addBooks();
},
},
};
</script>
+100
하여 쉽게 바닥을 인식할 수 있게 해준다.