I know this is an old question, but I found a better solution with Vue.js 2.0+ Custom Directives: I needed to bind the scroll event too, then I implemented this.
First of, using @vue/cli
, add the custom directive to src/main.js
(before the Vue.js instance) or wherever you initiate it:
Vue.directive('scroll', {
inserted: function(el, binding) {
let f = function(evt) {
if (binding.value(evt, el)) {
window.removeEventListener('scroll', f);
}
}
window.addEventListener('scroll', f);
}
});
Then, add the custom v-scroll
directive to the element and/or the component you want to bind on. Of course you have to insert a dedicated method: I used handleScroll
in my example.
<my-component v-scroll="handleScroll"></my-component>
Last, add your method to the component.
methods: {
handleScroll: function() {
// your logic here
}
}
You don’t have to care about the Vue.js lifecycle anymore here, because the custom directive itself does.