Vue.js Respond to Scroll Position
February 15, 2021•97 words
// Simple example of how to get current scroll position, and update it live
// Usefull for stuff like parallax scrolling, and changing navbar on scroll
// If needed, you can get total height with: `document.body.scrollHeight`
// Licensed under WTFPL - (C) 2020 Alicia Sykes <https://aliciasykes.com/>
<template>
<div>
Scroll Position, from top: {{scrollPosition}}
</div>
</template>
<script>
export default {
name: 'ScrollComponent',
data: () => ({
scrollPosition: 0,
}),
methods: {
scroll () {
window.onscroll = () => {
this.scrollPosition = document.documentElement.scrollTop;
}
},
},
mounted() {
this.scroll();
},
beforeDestroy() {
window.removeEventListener('scroll', this.scroll);
}
}
</script>