实现一个返回页面顶部的 Vue3 组件

主要参考:Simple Vue.js and Tailwind.css Scroll To Top Button | Adam Bailey

CSS 库:Bootstrap V5.2

  • 按钮的布局方式为 sticky
  • 因为可能需要频繁切换显示状态,所以用v-show 而不是 v-if来控制按钮可见性
  • 使用 Vue 中内置的<transition>组件实现状态之间的平滑过渡
BackToTop.vue
vue
<template>
<div class="position-sticky bottom-0 end-0 w-100 d-flex justify-content-end b-0 pb-3 pe-5">
<transition>
<button class="btn btn-secondary btn-sm" v-show="isVisible" @click="scrollToTop" aria-label="scroll to top of the page">
<img src="../assets/to-top.min.svg" alt="an arrow point to top" />
</button>
</transition>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, onBeforeUnmount } from 'vue'
export default defineComponent({
name: 'BackToTop',
setup() {
const isVisible = ref(false)
const handleScroll = () => {
isVisible.value = window.scrollY > 0
}
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
})
}
onMounted(() => {
window.addEventListener('scroll', handleScroll)
})
onBeforeUnmount(() => {
window.removeEventListener('scroll', handleScroll)
})
return {
isVisible,
handleScroll,
scrollToTop
}
}
})
</script>
<style>
.v-enter-active,
.v-leave-active {
transition: opacity 0.2s ease;
}
.v-enter-from,
.v-leave-to {
opacity: 0;
}
</style>
to-top.min.svg
html
<svg width="20" height="20" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M24.008 14.1V42M12 26l12-12 12 12M12 6h24"
stroke="#fff"
stroke-width="4"
stroke-linecap="round"
stroke-linejoin="round" />
</svg>

其他参考/实现方式:

题外话:BootStrap 的文档写得好烂

%sveltekit.body%