vue 滚动监听

data () {
  return {
    scrolled: false
  };
},
methods: {
  handleScroll () {
    this.scrolled = window.scrollY > 0;
  }
},
mounted() {
  window.addEventListener('scroll', this.handleScroll);
}

我看网上说,这样写,始终没什么用。

clipboard.png
document.body.scrollTop也始终都为0

求大神。

阅读 5.4k
4 个回答

在mounted中进行window的滚动绑定

我正好做过一个,要动态更改数据必须要把先定义一个动态变量,写在data里面:

    data: function() {
      return {
        scrollTop:0,//滚动条位置
        offsetHeight:0,//可视区高
        scrollHeight:0,//滚动区域
      }
    },
    watch:{
        //观察滚动条位置
      scrollTop:function(){
        // console.log("当前滚动条高"+this.scrollTop);
        // console.log("可视区高"+this.offsetHeight);
        // console.log("滚动条高"+this.scrollHeight);
      }
    },
    
    methods: {
      //同步滚动条与body 滚动条状态
      bindScroll:function(){
          //console.log(document.body.scrollTop);
          this.scrollTop=document.body.scrollTop;
          this.scrollHeight=document.body.scrollHeight;
          this.offsetHeight=document.body.offsetHeight;
        }
    },
    //我这个是使用了<keep-alive > 所以组件里监听写在这里,你可以写在mounted里面
    activated: function(){
        //监听滚动
        console.log("激活keep-alive,监听滚动")
        window.addEventListener("scroll",this.bindScroll);
    },
    deactivated: function(){
        console.log("节点停用keep-alive,解除监听");
        window.removeEventListener("scroll",this.bindScroll);
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题