Vue3吸顶导航的实现
吸顶导航实现
【实现目标】:
在Layout页面中,浏览器上下滚动时,距离顶部距离大于80px吸顶导航显示,小于则隐藏。
【实现过程】:
-
通过layout接口获取分类列表内容并使用categorystore进行状态管理,获取到内容进行页面渲染。
-
在外层包裹stick,内层放置RouterLink渲染导航跳转,使用v-on的类名增强控制 stick的show属性
-
安装VueUse,参考官方手册:VueUse,导入useScroll函数,此处只用获取窗口的y坐标,来控制show属性是否生效
-
更改stick的样式,状态一:向上平移+完全透明;状态二:show属性生效时,移除平移+完全不透明
-
此处增加了一个插值表达式
{{y}}
来监视目前y坐标值
<script setup>
// 获取滚动距离
import { useScroll } from '@vueuse/core'
const { y } = useScroll(window)import { useCategoryStore } from '@/stores/categoryStore'
const categoryStore = useCategoryStore()
</script><template><div class="app-header-sticky" :class="{ show: y > 80 }"><div class="container"><RouterLink class="logo" to="/" />{{ y }}<!-- 导航区域 --><ul class="app-header-nav"><li class="home"><RouterLink to="/">首页</RouterLink></li><li class="home" v-for="item in categoryStore.categoryList" :key="item.id"><RouterLink active-class="active" :to="`/category/${item.id}`">{{item.name}}</RouterLink></li></ul></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;}.container {display: flex;align-items: center;}.logo {width: 200px;height: 80px;background: url('@/assets/images/logo.png') no-repeat right 2px;background-size: 160px auto;}
}.app-header-nav {width: 820px;display: flex;padding-left: 40px;position: relative;z-index: 998;li {margin-right: 40px;width: 38px;text-align: center;a {font-size: 16px;line-height: 32px;height: 32px;display: inline-block;&:hover {color: pink;border-bottom: 1px solid pink;}}.active {color: pink;border-bottom: 1px solid $Color;}}
}
</style>