vue3中监听el-scrollbar滚动的距离 , 实现点击回到顶部
![](https://i-blog.csdnimg.cn/blog_migrate/3b5a42dd3b2327707f62a474d9a53222.gif)
<template>
<el-scrollbar ref="scrollbar" @scroll.native="handleScroll">
<div class="model">
...页面的详细
</div>
<div @click="scrollTop" class="backToTopBtn" v-show="showBackToTop">回到顶部</div>
</el-scrollbar>
</template>
<script setup>
import { ref } from 'vue';
const scrollbar = ref(null);
const showBackToTop = ref(false);
const scrollTop = () => {
scrollbar.value.scrollTo({ top: 0, behavior: 'smooth' }); // 点击回到顶部
};
const handleScroll = () => {
if (scrollbar.value.$refs.wrapRef.scrollTop > 10) {
showBackToTop.value = true; // Vue3ref定义的数据需.value调用
} else {
showBackToTop.value = false;
}
console.log(scrollbar.value.$refs.wrapRef.scrollTop); // 屏幕滚动的距离
};
</script>
<style lang="less" scoped>
.backToTopBtn {
margin: 0 auto;
position: fixed;
bottom: 30px;
width: 30px;
height: 30px;
right: 30px;
background: url('../../assets/icon/回到顶部.svg') no-repeat;
background-size: 30px;
}
</style>