话不多说,代码奉上
Vue3的模板写法
<template>
<!-- 其它代码 -->
<view class="top-back" @click="topBack" v-if="isShow">
<text>^</text>
<text>顶部</text>
</view>
<template>
在 Vue 3 中,setup 是 Composition API(组合式 API) 的核心函数,它替代了 Vue 2 的 data、methods、computed 等选项,提供更灵活的代码组织方式。
<script setup>
import {
onLoad,
onPageScroll
} from '@dcloudio/uni-app';
const isShow = ref(false);
// 根据滚动距离以推断是否有显示返回顶部功能
onPageScroll((e) => {
console.log('Scroll position:', e.scrollTop);
if (e.scrollTop >= 200) {
isShow.value = true;
} else {
isShow.value = false;
}
});
// 点击绑定的事件
const topBack = () => {
uni.pageScrollTo({
scrollTop: 0, // 滚动到顶部
duration: 300 // 动画时长 300ms
});
};
如果依旧使用vue2语法的,可以参考此博主的写法:uni-app 如何实现回到页面顶部
样式如下
.top-back {
position: fixed;
right: 30rpx;
bottom: 120rpx;
width: 80rpx;
height: 80rpx;
background: rgba(0, 0, 0, 0.5);
border-radius: 50%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: white;
font-size: 28rpx;
z-index: 999;
}
效果图如下
功能已经实现,现在可以根据自身需要修改样式啦。