功能
- 点击后父组件页面回到顶部
- 父组件页面滚动的距离大于等于页面的一半时组件显示,否则隐藏
代码
<template>
<view class="back-to-top" :style="{ opacity: showBackToTop ? 1 : 0 }" @click="backToTop">
<text>Top</text>
</view>
</template>
<script setup>
import { ref, onMounted, computed, watch, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
const { proxy } = getCurrentInstance();
const example = proxy;
let windowHeight = 0;
onMounted(() => {
windowHeight = uni.getSystemInfoSync().windowHeight;
});
const props = defineProps({
pageScrollingDistance: {
type: Number,
required: true,
},
});
let showBackToTop = ref(false);
watch(
() => props.pageScrollingDistance,
(val) => {
if (val >= windowHeight / 2) {
showBackToTop.value = true;
} else {
showBackToTop.value = false;
}
}
);
function backToTop() {
uni.pageScrollTo({
scrollTop: 0,
duration: 300,
});
}
</script>
<style lang="scss" scoped>
.back-to-top {
position: fixed;
bottom: 20rpx;
right: 20rpx;
border-radius: 50%;
background: #ccc;
padding: 20rpx;
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
transition: opacity 0.3s;
opacity: 0;
text {
color: #fff;
}
}
</style>
页面使用
import { onPageScroll } from '@dcloudio/uni-app';
<backToTop :pageScrollingDistance="pageScrollingDistance"></backToTop>
import backToTop from './backToTop.vue';
let pageScrollingDistance = ref(0);
onPageScroll((e) => {
pageScrollingDistance.value = Math.ceil(e.scrollTop);
});