-
-
Save unixc3t/d6b654f74ac4eb4d2f1db7be3c094d31 to your computer and use it in GitHub Desktop.
Vue - onScrollBottom composable function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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