Skip to content

Instantly share code, notes, and snippets.

@Akryum
Created December 15, 2019 14:40
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Akryum/ae7aa882d674f80fdf85837f3c8949e3 to your computer and use it in GitHub Desktop.
Save Akryum/ae7aa882d674f80fdf85837f3c8949e3 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