The effect

Manual implementation

Js core code

<script>
import { onMounted, onUnmounted, ref } from 'vue'
export default{... setup () {// Define a reactive data
    const y = ref(0)
    const update = () = > {
      y.value = document.documentElement.scrollTop
      console.log(y.value)
    }
    onMounted(() = > { window.addEventListener('scroll', update) })
    onUnmounted(() = > { window.removeEventListener('scroll', update) })

    return { y }
  }
}
</script>
Copy the code

Add dynamic class Settings where needed

<div class="app-header-sticky" :class="{show:y>=78}">
Copy the code

Integral component code

<template>
  <div class="app-header-sticky" :class="{show:y>=78}">
    <div class="container">
      <Test />// You can pass in components that need to be topped</div>
  </div>
</template>

<script>
import Test from '@/views/test.vue'
import { onMounted, onUnmounted, ref } from 'vue'
export default {
  components: {
    Test
  },
  setup () {
    // Define a reactive data
    const y = ref(0)
    const update = () = > {
      y.value = document.documentElement.scrollTop
      console.log(y.value)
    }
    onMounted(() = > { window.addEventListener('scroll', update) })
    onUnmounted(() = > { window.removeEventListener('scroll', update) })

    return { y }
  }
}
</script>

<style scoped lang='less'>
.app-header-sticky {
  width: 100%;
  height: 80px;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  background-color: #fff;
  border-bottom: 1px solid #e4e4e4; // Hide by defaulttransform: translateY(-100%);
  opacity: 0; // CSS displays &.show {
    transition: all 0.3 s linear;
    transform: none;
    opacity: 1;
  }
  .container {
    display: flex;
    align-items: center; }}</style>
Copy the code

Borrow tools to do that

Tool library

Vueuse /core is a third-party logic library used in conjunction with the Vue3 composite API implemented using vueuse libraries :vueuse.org/guide/index… Know the use of useWindowScroll

How to use

1. Install

npm i @vueuse/core
Copy the code

2. Use

<script>
UseWindowScroll () is an API provided by @vueuse/core that returns the x and y dimensions of the scroll bar
import { useWindowScroll } from '@vueuse/core'
export default {
  name: 'AppHeaderSticky',
  setup () {
    const { y } = useWindowScroll()
    return { y }
  }
}
</script>
Copy the code

3. Summary