基于 Vue2 和 TypeScript 开发的“回到顶部”功能组件
<template>
<div class="back-to-top" v-show="show" @click="goTop">
<i class="iconfont icon-arrow-up"></i>
</div>
</template>
<script lang="ts">
import {
Component, Vue } from 'vue-property-decorator'
@Component
export default class BackToTop extends Vue {
show = false // 是否显示返回顶部按钮
// 监听页面滚动事件
mounted() {
window.addEventListener('scroll', this.handleScroll)
}
// 移除滚动事件监听
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
// 处理页面滚动事件
handleScroll() {
this.show = window.pageYOffset > 100 // 当页面滚动距离超过100px时,显示返回顶部按钮
}
// 回到页面顶部
goTop() {
window.scrollTo({
top: 0, behavior: 'smooth' }) // 平滑滚动到页面顶部
}
}
</script>
<style scoped>
.back-to-top {
position: fixed;
bottom: 50px;
right: 50px;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
font-size: 20px;
color: #fff;
background-color: #555;
border-radius: 50%;
cursor: pointer;
opacity: 0.5;
transition: opacity 0.3s;
}
.back-to-top:hover {
opacity: 0.8;
}
</style>
具体实现思路是监听页面滚动事件,当滚动距离超过100px时,显示返回顶部按钮。点击按钮时,通过平滑滚动到页面顶部的方式回到顶部。其中,使用了阿里巴巴的 Iconfont 图标库,展示了一个上升的箭头图标。
需要注意的是,组件样式需要通过 scoped 属性实现局部作用域,避免影响到其他组件的样式。
以上是一个基本的回到顶部功能组件,您可以根据实际需求对其进行更改和扩展。