Watch window.scrollY changes in Vuejs

前端 未结 4 1715
野趣味
野趣味 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条回答
  • 2021-02-15 18:02

    window properties can't be used reactively like that. Instead, you'd have to listen to the window's scroll event and respond accordingly:

    mounted() {
      window.addEventListener("scroll", this.onScroll)
    },
    beforeDestroy() {
      window.removeEventListener("scroll", this.onScroll)
    },
    methods: {
      onScroll(e) {
        this.windowTop = window.top.scrollY /* or: e.target.documentElement.scrollTop */
      }
    }
    

    0 讨论(0)
  • 2021-02-15 18:08

    2020 Updated:

    Use @scroll.passive to watch scroll of any element in component:

    Example:

    Template

    <div class="room_message-stream" @scroll.passive="handleScroll">
          <ul class="room_message-stream__list">
            <li class="room_message-stream__list-item">...</li>
          </ul>
    </div>
    

    Methods:

    handleScroll (e) {
      var scrollPos = e.target.scrollTop
    }
    
    0 讨论(0)
  • 2021-02-15 18:11

    You can use the mounted() method to add your event listener to the window object like this:

    var p = new Vue({
       el: "#app",
       data(){
          return {
              windowTop: 0
          };
       },
       mounted()
       {
           var that = this;
           window.addEventListener("scroll", function(){
               that.windowTop = window.scrollY;
           });
       },
       template: "<div style='height: 250vh'><div style='position: fixed; right: 0; top: 0'>{{windowTop}}</div></div>"
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app"></div>

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题