1) Install the @vueuse/core package, which encapsulates some common interaction logic
NPM i@vueuse /[email protected] // Here must be careful to lock the version, because the latest version has some content incompatible with the projectCopy the code
2) Use SRC /components/header-sticky. Vue in top navigation
<template> <div class="app-header-sticky" :class="{show:top >= 78}"> <div class="container" v-if='top>=78'> <RouterLink Class ="logo" to="/" /> <HeaderNav /> <div class="left"> <RouterLink to="/" > <RouterLink to="/" > thematic </RouterLink> </div> </div> </template> <script> import HeaderNav from './header-nav' import {useWindowScroll } from '@vueuse/core' export default { name: 'AppHeaderSticky', components: Const {y: top} = useWindowScroll() return {top}} </script>Copy the code
In addition to using a third party to achieve the top function, we can also use the native method to achieve, here is also given code for your reference:
src/layout/components/header-sticky.vue
<template> <! --> <TopNav /> <! -- Header area --> < header /> <! --> <HeaderSticky/> <main> <! - secondary routing exports - > < the router - the view > < / router - the view > < / main > <! -- Bottom footer --> < footer /> </template> <script> import TopNav from './components/top-nav' import Header from './components/header' import Footer from './components/footer' import HeaderSticky from '@/components/header-sticky' export default { name: 'XtxLayout', components: { AppTopnav, AppHeader, AppFooter, HeaderSticky } } </script>Copy the code
3) Scroll to 78px to complete the display (add the class name)
Check in the callback function to see if 78px has been scrolled (78 because the height of my project’s top navigation bar is 78, depending on my project), add the class name if it is larger, remove the class name otherwise
- Document. The documentElement. ScrollTop the rolling distance
- :class Dynamically controls the display of class names
.app-header-sticky { width: 100%; height: 80px; position: fixed; left: 0; top: 0; z-index: 999; background-color: #fff; Border-bottom: 1px solid #e4e4e4; border-bottom: 1px solid #e4e4; border-bottom: 1px solid #e4e4e4 opacity: 0; &.show {transition: all 0.3s linear; transform: none; opacity: 1; }Copy the code
Add class names dynamically by controlling the scrolling distance
import TopNavCommon from '@/components/top-nav-common' export default { name: 'AppHeaderSticky', components: { TopNavCommon }, setup () { const top = ref(0) window.onscroll = () => { const scrollTop = document.documentElement.scrollTop top.value = scrollTop } return { top } } }Copy the code
<template>
<div class="app-header-sticky" :class='{show: top>=78}'>
<div class="container" v-if='top>=78'>
Copy the code
Conclusion:
- By default, components appear at the top of the page, out of view
- When the page scrolls beyond 78px, add a class name that controls the display of the top component