在vue中實現滾動監聽和原生js無太大差別,下面是一個簡單的demo,可在控制檯查看結果javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script> <style type="text/css"> #box { width: 100%; height: 2000px; } </style> </head> <div id="box"></div> <body> <!-- vue監聽滾動事件 --> <script type="text/javascript"> var vm = new Vue({ el:'#box', data() { return { scroll: '' } }, methods: { menu() { this.scroll = document.documentElement.scrollTop || document.body.scrollTop; console.log(this.scroll) } }, mounted() { window.addEventListener('scroll', this.menu) }, }) </script> </body> </html>