intersection observer - OhMinsSup/tip-review GitHub Wiki
[https://heropy.blog/2019/10/27/intersection-observer/]
new Vue({
el: '#app',
data () {
return {
photos: [],
length: 4,
showScrollObserver: true
}
},
created () {
this.fetchPhotos(1, this.length)
.then(() => {
this.initIntersectionObserver()
})
// For next photo
this.increasePhotoLength()
},
methods: {
/**
* @summary μ¬μ§μ κ°μ Έμ΅λλ€.
* @param {number} start - κ°μ Έμ¬ μ¬μ§μ μμ ν¬μΈνΈ
* @param {number} limit - κ°μ Έμ¬ μ¬μ§μ κ°μ
* @return {Promise} - λΉλκΈ° μ€νμ μν Promise κ°μ²΄
*/
fetchPhotos (start = 1, limit = 1) {
return new Promise(resolve => {
const photosToFetch = []
for (let i = start; i < start + limit; i += 1) {
photosToFetch.push(
axios(`https://jsonplaceholder.typicode.com/photos/${i}`)
)
}
Promise.all(photosToFetch)
.then(photos => {
return photos.map(photo => {
return {
...photo.data,
imageLoaded: false
}
})
})
.then(photos => {
this.photos.push(...photos)
this.photos.forEach(photo => {
// μ¬μ§ λ‘λλ₯Ό λκΈ°
const image = new Image()
image.src = photo.url
image.onload = () => {
photo.imageLoaded = true
}
})
resolve(true)
})
})
},
/**
* @summary Intersection Observerλ₯Ό μ΄κΈ°νν©λλ€.
*/
initIntersectionObserver () {
const io = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
// μμ(#scroll-observer)μ κ°μμ±μ΄ ν보λλ©΄..
if (entry.isIntersecting) {
this.fetchPhotos(this.length)
// For next photo
this.increasePhotoLength()
}
})
}, {
// 'Codepen'μ 'JSFiddle'μμλ μ΅μ
μ΄ μ λλ‘ λμνμ§ μλκ΅°μ.
// μ΅μ
μ λν ν
μ€νΈλ 'JSBin'μ΄λ λ‘컬μμ μ§ννμλ©΄ λ©λλ€.
// λ‘λ© μ λλ©μ΄μ
μ΄ λ³΄μ΄μ§ μκ² κ°μ Έμ€κΈ°λ₯Ό μνν μ μλλ‘..
// rootMargin: '0px 0px 400px 0px'
})
io.observe(this.$refs.scrollObserver)
},
/**
* @summary κ°μ Έμ¬ μ¬μ§μ μμ ν¬μΈνΈλ₯Ό μ¦κ°μν΅λλ€.
*/
increasePhotoLength () {
this.length += 1
console.log(this.length)
}
}
})