1. 给出静态模板
2. 吸顶导航出现前 将它上移自身高度的100% 且透明度为零 实现隐藏
当鼠标滚动到一定距离时 将它返回原位 用transition实现过渡效果
<template>
<div class="app-header-sticky" :class="{ show: y > 78 }">
<div class="container">
<RouterLink class="logo" to="/" />
<!-- 导航区域 -->
<ul class="app-header-nav">
<li class="home">
<RouterLink to="/">首页</RouterLink>
</li>
<li
class="home"
v-for="item in categoryStore.getCategoryList"
:key="item.id"
>
<RouterLink active-class="active" :to="`/category/${item.id}`">{{
item.name
}}</RouterLink>
</li>
</ul>
<div class="right">
<RouterLink to="/">品牌</RouterLink>
<RouterLink to="/">专题</RouterLink>
</div>
</div>
</div>
</template>
<style scoped lang="scss">
.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;
// 状态二:移除平移 + 完全不透明
&.show {
transition: all 0.3s linear;
transform: none;
opacity: 1;
}
<style/>
3. 吸顶导航和页面头部的导航渲染可以写在pinia仓库中 便于两个页面复用
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getCategoryAPI } from '@/api/layout.js'
export const useCategoryStore = defineStore('category', () => {
const getCategoryList = ref([])
const getCategory = async () => {
const res = await getCategoryAPI()
getCategoryList.value = res.result
}
return { getCategoryList, getCategory }
})
<script setup>
import { useScroll } from '@vueuse/core'
import { useCategoryStore } from '@/stores/category.js'
const categoryStore = useCategoryStore()
const { y } = useScroll(window)
</script>