1、点击按钮滚动到页面头部
hooks文件夹>useBackTop.js
import { ref } from 'vue';export default function useBackTop() {const scrollTop = ref(0);const backTopFlag = ref(false);const scrollToTop = () => {scrollTop.value = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;// 为了计算距离顶部的高度,当高度大于60显示回顶部图标,小于60则隐藏backTopFlag.value = scrollTop.value > 60;};const goBackTop = () => {window.scrollTo({top: 0,behavior: 'smooth',});};window.addEventListener('scroll', scrollToTop);return {scrollToTop,backTopFlag,goBackTop,};
}
页面中使用
<template><div v-if="backTopFlag" class="return-top" @click="goBackTop"></div>
</template>
<script setup>
import useBackTop from '@/hooks/useBackTop';
const {backTopFlag,goBackTop,
} = useBackTop();
</script>
2、tabs滚动监听亮显、点击锚点跳转
安装瞄点定位插件依赖
npm i smooth-scroll-into-view-if-needed
hooks文件夹>useBackTop.js
import { ref, onBeforeUnmount } from 'vue';
import scrollIntoView from 'smooth-scroll-into-view-if-needed';export default function useScroll(navList) {const navCurrent = ref(navList[0]?.value);navCurrent.value = navList[0]?.value;const isFixed = ref(false);const scrollNav = (sections) => {const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; // 滚动条偏移量// 导航吸顶const weTabs = document.querySelector('.wd-tabs').offsetTop;isFixed.value = scrollTop >= weTabs;sections.forEach((item, index) => {if (item.offsetTop - 100 <= scrollTop) {navCurrent.value = navList[index].value;}});};const navigate = (tab) => {navCurrent.value = tab;const node = document.querySelector(`.${tab}`);scrollIntoView(node, {scrollMode: 'if-needed',block: 'start',inline: 'nearest',});};document.onscroll = () => {scrollNav(document.querySelectorAll('.scroll-item'));};onBeforeUnmount(() => {document.onscroll = '';});return {isFixed,navCurrent,navigate,scrollNav,};
}
页面中使用
<template><div class="page"><div class="wd-tabs"><div class="wd-tabs-content" :class="{ fixed: isFixed }"><div class="main-content wd-advice"><div v-for="(item,index) in navList" :key="index" class="tabs-item" :class="{ active: navCurrent === item.value } " @click="navigate(item.value)"><div class="name">{{item.title}}</div></div></div></div></div><div class="scroll-item" v-for="(item, index) in navList":key="index" :class="item.value">{{item.title}}</div></div>
</template>
<script setup>
import { ref, computed, onBeforeMount } from 'vue';
import { useRoute } from 'vue-router';
import useScroll from '@/hooks/useScroll';const route = useRoute();
const id = computed(() => route.params.id);const navList = ref([{ title: '产品优势', value: 'advantages' },{ title: '产品功能', value: 'features' },{ title: '产品架构', value: 'architecture' },{ title: '应用场景', value: 'scenario' },{ title: '业务案例', value: 'business' },{ title: '产品动态', value: 'dynamics' },
]);
const {isFixed,navCurrent,navigate,
} = useScroll(navList.value);onBeforeMount(async () => {});
</script>