回到顶部
基础用法
vue
<BackTop />
自定义内容
vue
<BackTop>
<div class="back-to-top-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="#00aaff" d="M4 4h16v2H4zm8 3.586l6.914 6.914l-1.414 1.414l-4.5-4.5V21h-2v-9.586l-4.5 4.5L5.086 14.5z"/></svg>
</div>
</BackTop>
回到顶部功能实现代码
查看代码
vue
<template>
<teleport :to="target">
<div class="back-to-top" ref="backToTopRef" @click="backToTop" v-show="show" :title="tipsTitle">
<slot v-if="$slots.default"></slot>
<div v-else>
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
<path fill="#00aaff"
d="M4 4h16v2H4zm8 3.586l6.914 6.914l-1.414 1.414l-4.5-4.5V21h-2v-9.586l-4.5 4.5L5.086 14.5z" />
</svg>
</div>
</div>
</teleport>
</template>
<script setup>
import { defineOptions, defineProps, onMounted, onUnmounted, ref } from 'vue';
defineOptions({
name: 'BackTop'
})
const props = defineProps({
target: {
type: String,
default: 'body'
},
tipsTitle: {
type: String,
default: '回到顶部'
},
visibilityHeight: {
type: Number,
default: 100
},
bottom: {
type: String,
default: '40px'
},
right: {
type: String,
default: '40px'
}
})
const backToTopRef = ref(null)
const show = ref(false)
const el = ref(null)
onMounted(() => {
el.value = document.querySelector(props.target)
if (!el.value) {
console.warn(`target is not existed: ${props.target}`)
}
})
const backToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
})
}
const scrollFn = () => {
show.value = window.scrollY > props.visibilityHeight
}
onMounted(() => {
window.addEventListener('scroll', scrollFn)
})
onUnmounted(() => {
window.removeEventListener('scroll', scrollFn)
})
</script>
<style lang="scss" scoped>
.back-to-top {
position: fixed;
z-index: 9999;
right: v-bind(right);
bottom: v-bind(bottom);
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #fff;
box-shadow: 0 0 6px rgba(0, 0, 0, 0.12);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
</style>
配置说明
属性
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
right | 距离右侧距离 | number | 20 |
bottom | 距离底部距离 | number | 20 |
target | 触发元素 | string | body |
visibilityHeight | 显示高度 | number | 100 |
tipsTitle | 提示文字 | string | 回到顶部 |
插槽
名称 | 说明 |
---|---|
default | 自定义内容 |