0

Am using vuejs2 with codeigniter.

I have added the following to the html

<header id="test_header">
     my nav menu
</header>   

In a separate scripts.js i have

script.js

new Vue({
 el: '#test_header',
 data:function(){
  return{

  }
},
methods:{
    handleScroll(){
        console.log("on scroll");
    },
    listenScroll(){
        window.addEventListener("scroll", this.handleScroll);
    }
},
mounted() {
  this.listenScroll();
},
destroyed () {
    window.removeEventListener('scroll', this.handleScroll);
}
});

Am trying to listen to the scroll event but the function is only executed once. That is console.log("on scroll") executes only during mount but the function is never executed when the page scrolls

i have included the javascript files in the html in the following order

<html> 
  <body> 
   <script src="vuejs.js"> //includes vuejs frameworks
   <script src="script.js"> ///includes above code
  </body>
 </html>

What am i missing?

Geoff
  • 6,277
  • 23
  • 87
  • 197

1 Answers1

1

Create the event listener for the scroll event in created()

ex

  created(){
    window.addEventListener("scroll", this.myFunction);
  }

Also you methods object should look like:

{
  myFunction: function(){},
  anotherFunction: function(){}
}

Working js fiddle

Kevin Hernandez
  • 1,270
  • 2
  • 19
  • 41
  • Thanks it works but i had to add passive true like window.addEventListener("scroll", this.myFunction,true); to remove a warning "Added non-passive event listener to a scroll-blocking 'touchstart' event" – Geoff May 21 '19 at 03:57