Skip to content

Instantly share code, notes, and snippets.

@unixc3t
Forked from Akryum/List.vue
Created December 16, 2019 03:00
Show Gist options
  • Save unixc3t/d6b654f74ac4eb4d2f1db7be3c094d31 to your computer and use it in GitHub Desktop.
Save unixc3t/d6b654f74ac4eb4d2f1db7be3c094d31 to your computer and use it in GitHub Desktop.
Vue - onScrollBottom composable function
<script>
import { ref } from '@vue/composition-api'
import { onScrollBottom } from '@/scroll'
export default {
setup () {
function loadMore () {
// ...
}
const el = ref()
onScrollBottom(loadMore, el, 600)
return {
el,
}
}
}
</script>
import { onUnmounted, watch } from '@vue/composition-api'
function getScrollParent (node) {
if (node == null) {
return null
}
if (node.scrollHeight > node.clientHeight) {
if (node === document.documentElement) {
return { emitter: document, scroller: document.documentElement }
}
return { emitter: node, scroller: node }
} else {
return getScrollParent(node.parentNode)
}
}
export function onScrollBottom (handler, el, offsetFromBottom) {
let scrollParent
function onScroll () {
const { scroller } = scrollParent
if (scroller.scrollTop >= scroller.scrollHeight - scroller.clientHeight - offsetFromBottom) {
handler()
}
}
function addListeners () {
removeListeners()
if (!el.value) return
scrollParent = getScrollParent(el.value)
if (scrollParent) {
scrollParent.emitter.addEventListener('scroll', onScroll)
}
}
function removeListeners () {
if (scrollParent) {
scrollParent.emitter.removeEventListener('scroll', onScroll)
}
}
watch(el, () => {
addListeners()
})
onUnmounted(() => {
removeListeners()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment