在vue中实现滚动监听和原生js无太大差异,下面是一个简单的demo,可在控制台查看结果
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>Document</title> 7 <script type="text/javascript" src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script> 8 <style type="text/css"> 9 #box { 10 width: 100%; 11 height: 2000px; 12 } 13 </style> 14 </head> 15 <div id="box"></div> 16 17 <body> 18 <!-- vue监听滚动事件 --> 19 <script type="text/javascript"> 20 var vm = new Vue({ 21 el:'#box', 22 data() { 23 return { 24 scroll: '' 25 } 26 }, 27 methods: { 28 menu() { 29 this.scroll = document.documentElement.scrollTop || document.body.scrollTop; 30 console.log(this.scroll) 31 } 32 }, 33 mounted() { 34 window.addEventListener('scroll', this.menu) 35 }, 36 }) 37 </script> 38 </body> 39 40 </html>