[Vuejs]-Vue.js(2) window.scrollY always return 0

0👍

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

Leave a comment