Watch window.scrollY changes in Vuejs

前端 未结 4 1700
野趣味
野趣味 2021-02-15 17:42

I have a very simple app, that has 2 components: the App.vue and another component, Home.vue where I hold the rest of the structure of the app: a stick

4条回答
  •  -上瘾入骨i
    2021-02-15 18:13

    For me none of the above worked.

    I had to pass true as 3rd parameter in add/remove scroll listener:

    mounted() {
      window.addEventListener("scroll", this.onScroll, true)
    },
    beforeDestroy() {
      window.removeEventListener("scroll", this.onScroll, true)
    },
    methods: {
      onScroll(e) {
        this.windowTop = e.target.scrollTop;
      }
    }
    

    3rd parameter: You should be able to attach a document-level listener with a third parameter of true to capture the scroll events on all elements. Here's what that looks like:

    document.addEventListener('scroll', function(e){ }, true);
    

    The true at the end is the important part, it tells the browser to capture the event on dispatch, even if that event does not normally bubble, like change, focus, and scroll.

提交回复
热议问题