Search code examples
javascriptvue.jsvue-routervuestic-admin

vue.js(2) window.scrollY always return 0


I've got some questions about vuejs and router ..

  1. window.addEventListener('scroll', ...) also is not detected in my component.
  2. When I typed 'window.scrollY' in console.log. It will always return 0 back to me.
  3. Right scroll(Y) are available and window.innerHeight is not equal 0
  4. I can't detected when client move scroll to bottom
  5. I use vuestic and vue-router Thank you
  created () {
    // Not working because window.scrollY always return 0
    window.addEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll (event) {}
  }

Solution

  • you can try to listen for scrolling a child element.

    and using getBoundClientRect:

    <template>
      <div id="app">
        <nav>navbar</nav>
        <main id="listen">main</main>
      </div>
    </template>
    
    <script>
    export default {
      name: "App",
      created() {
        document.addEventListener("scroll", this.listenScroll);
      },
      destroyed() { // remember to remove the listener when destroy the components
        document.removeEventListener("scroll", this.listenScroll);
      },
      methods: {
        listenScroll() {
          let myScroll = document.querySelector("#listen").getBoundingClientRect()
            .top;
          console.log(myScroll);
        },
      },
    };
    </script>
    
    <style>
    nav {
      height: 100px;
    }
    main {
      height: 700px;
    }
    </style>
    
    

    here there is a codesandbox https://codesandbox.io/s/great-hill-x3wb1?file=/src/App.vue:0-560