How to apply different styles when scroll up and down in vue 3?

Solution 1:

You can use Template Refs.

Here's a few example using your code :

<template>
  <!-- assign a reference to html element using ref attribute -->
  <header ref="headRef"></header>
</template>
  • Using Options API
<script>
  export default {
    methods: {
      vueOnScroll() {
        var prev = window.pageYOffset;
        const refs = this.$refs.headRef; // assign the reference in variable
        window.addEventListener("scroll", () => {
          var curr = window.pageYOffset;
          if (prev > curr) {
            refs.classList.add("scrolled");
            refs.classList.remove("scrollDown");
          } else {
            refs.classList.add("scrollDown");
            refs.classList.remove("scrolled");
          }
          if (curr === 0) {
            refs.classList.remove("scrollDown");
            refs.classList.remove("scrolled");
          }
            prev = curr;
        });
      },
    },
    mounted() {
      // run the function when the component's mount
      this.vueOnScroll();
    }
  }
</script>

  • Using Composition API
<script>
  import { ref } from "@vue/reactivity";
  import { onMounted } from "@vue/runtime-core";

  export default {
    setup() {
      const headRef = ref(null); // obtain the reference
      onMounted(() => {
        var prev = window.pageYOffset;
        window.addEventListener("scroll", () => {
          var curr = window.pageYOffset;
          if (prev > curr) {
            headRef.value.classList.add("scrolled");
            headRef.value.classList.remove("scrollDown");
          } else {
            headRef.value.classList.add("scrollDown");
            headRef.value.classList.remove("scrolled");
          }
          if (curr === 0) {
            headRef.value.classList.remove("scrollDown");
            headRef.value.classList.remove("scrolled");
          }
          prev = current;
        });
      });
      return { headRef };
    },
  };
</script>