简单封装一个吸顶组件 ( Vue3 )

2,419 阅读1分钟

效果

image.png

手动实现

js实现核心代码

<script>
import { onMounted, onUnmounted, ref } from 'vue'
export default {
  ...
  setup () {
    // 定义一个响应式数据
    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>

在需要使用的地方补充动态设置class

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

整体组件代码

<template>
  <div class="app-header-sticky" :class="{show:y>=78}">
    <div class="container">
      <Test /> // 可以传入自己需要吸顶的组件
    </div>
  </div>
</template>

<script>
import Test from '@/views/test.vue'
import { onMounted, onUnmounted, ref } from 'vue'
export default {
  components: {
    Test
  },
  setup () {
    // 定义一个响应式数据
    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;
  // 默认隐藏
  transform: translateY(-100%);
  opacity: 0;
  // css显示
  &.show {
    transition: all 0.3s linear;
    transform: none;
    opacity: 1;
  }
  .container {
    display: flex;
    align-items: center;
  }
}
</style>

借用工具来实现

工具库

@vueuse/core是配合vue3组合式API一起使用的一个第三方逻辑库
使用vueuse工具库来实现:vueuse.org/guide/index…
了解useWindowScroll的用法

如何使用

1.安装

npm i @vueuse/core

2.使用

<script>
// useWindowScroll()是@vueuse/core提供的api可返回当前页面滚动时候滚动条的x横向、y纵向
import { useWindowScroll } from '@vueuse/core'
export default {
  name: 'AppHeaderSticky',
  setup () {
    const { y } = useWindowScroll()
    return { y }
  }
}
</script>

3.小结

image.png