How to Create a Custom Scroll Event in Vue
Jul 30, 2021
You can handle scrolling in Vue with custom directives.
Below is a live example of a Vue instance that prints the current value of window.scrollY
.
Scroll down and the value below should increment.
Scroll and Watch
The value of window.scrollY
: {{ value }}!
Below is the JavaScript code.
Calling Vue.directive('scroll')
registers a v-scroll
directive that you can use in your HTML templates.
And binding.value
contains the computed value of the v-scroll
attribute.
In the below case, binding.value
points to the handleScroll()
method.
Vue.directive('scroll', {
inserted: function (el, binding) {
const onScrollCallback = binding.value;
window.addEventListener('scroll', () => onScrollCallback());
}
});
// main app
new Vue({
el: '#app',
data: {
value: 0
},
methods: {
handleScroll: function() {
this.value = window.scrollY;
}
}
});
Below is the HTML template. Note that v-scroll
needs to be a function.
<div id="app">
<h1>Scroll and Watch</h1>
<div v-scroll="handleScroll">
<p>The value of <code>window.scrollY</code>: {{ value }}!</p>
</div>
</div>
Vue School has some of our favorite Vue
video courses. Their Vue.js Master Class walks you through building a real
world application, and does a great job of teaching you how to integrate Vue
with Firebase.
Check it out!
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!