Skip to content

回到顶部

上次更新 2024年11月28日星期四 6:50:44 字数 0 字 时长 0 分钟

基础用法

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>

回到顶部功能实现代码

查看代码
index.vue
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距离右侧距离number20
bottom距离底部距离number20
target触发元素stringbody
visibilityHeight显示高度number100
tipsTitle提示文字string回到顶部

插槽


名称说明
default自定义内容