我正在使用 vuejs2 和 codeigniter。
我已将以下内容添加到 html
<header id="test_header">
my nav menu
</header>
在一个单独的scripts.js中我有
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);
}
});
我正在尝试监听滚动事件,但该函数仅执行一次。也就是说 console.log("onscroll") 仅在挂载期间执行,但当页面滚动时该函数永远不会执行
我已按以下顺序将 javascript 文件包含在 html 中
<html>
<body>
<script src="vuejs.js"> //includes vuejs frameworks
<script src="script.js"> ///includes above code
</body>
</html>
我错过了什么?
最佳答案
在created()
中创建滚动事件的事件监听器
例如
created(){
window.addEventListener("scroll", this.myFunction);
}
此外,您的方法对象应该如下所示:
{
myFunction: function(){},
anotherFunction: function(){}
}
关于javascript - Vuejs2监听页面滚动失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56230686/