vue 使用useWindowScroll实现首页布局中的吸顶效果

1、首先安装@vueuse/core

npm i @vueuse/core -s

2、新建一个HeaderSticky.vue文件,其内容为;

<template>
  <div class="app-header-sticky" :class="{show:y>=100}">
    <div class="container" v-show="y>=100">模拟titlediv>
  div>
template>

<script setup>
import { useWindowScroll } from '@vueuse/core'
import {watch} from "vue";

const { y } = useWindowScroll()
watch(y, (newVal)=>{
  console.log(y.value)
},{immediate:true})
script>

<style scoped lang="less">
.app-header-sticky{
  width: 100%;
  height: 100px;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  background-color: pink;
  transform: translateY(-100%);
  opacity: 0;
  &.show {
    transition: all 0.3s linear;
    transform: none;
    opacity: 1;
  }
  .container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    font-size: 20px;
  }
}
style>

3、在App.vue中写如下内容:

<template>
  <div class="body">
    <div class="header">模拟titlediv>
    <HeaderSticky>HeaderSticky>
    <div class="container">

    div>
  div>
template>

<script setup>
import {ref} from "vue";
import HeaderSticky from './components/HeaderSticky.vue'

script>
<style scoped lang="less">
.header{
  height: 100px;
  text-align: center;
  line-height: 100px;
  font-size: 20px;
  background-color: pink;
}
.container{
  height: 1000px;
  background-color: lightgrey;
}
style>

4、效果如下:

vue 使用useWindowScroll实现首页布局中的吸顶效果_第1张图片
当鼠标滑动到100px时会出现吸顶动画

你可能感兴趣的:(vue,前端,vue.js,javascript,前端)