cl-back-top.uvue 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <template>
  2. <view class="cl-back-top-wrapper" :style="{ bottom }">
  3. <view
  4. class="cl-back-top"
  5. :class="{
  6. 'is-show': visible
  7. }"
  8. >
  9. <cl-icon name="skip-up-line" color="white" size="25px"></cl-icon>
  10. </view>
  11. </view>
  12. </template>
  13. <script setup lang="ts">
  14. import { computed, onMounted, ref, watch, type PropType } from "vue";
  15. import { usePage } from "@/cool";
  16. defineOptions({
  17. name: "cl-back-top"
  18. });
  19. const props = defineProps({
  20. top: {
  21. type: Number as PropType<number | null>,
  22. default: null
  23. }
  24. });
  25. const page = usePage();
  26. const { screenHeight } = uni.getWindowInfo();
  27. // 是否显示回到顶部按钮
  28. const visible = ref(false);
  29. // 底部距离
  30. const bottom = computed(() => {
  31. let h = 20;
  32. if (page.hasCustomTabBar()) {
  33. h += page.getTabBarHeight();
  34. }
  35. return h + "px";
  36. });
  37. // 控制是否显示回到顶部按钮
  38. function update(top: number) {
  39. visible.value = top > screenHeight - 100;
  40. }
  41. onMounted(() => {
  42. if (props.top != null) {
  43. // 监听参数变化
  44. watch(
  45. computed(() => props.top!),
  46. (top: number) => {
  47. update(top);
  48. },
  49. {
  50. immediate: true
  51. }
  52. );
  53. } else {
  54. // 监听页面滚动
  55. page.onPageScroll((top) => {
  56. update(top);
  57. });
  58. }
  59. });
  60. </script>
  61. <style lang="scss" scoped>
  62. .cl-back-top {
  63. @apply flex flex-row items-center justify-center bg-primary-500 rounded-full;
  64. width: 40px;
  65. height: 40px;
  66. transition-property: transform;
  67. transition-duration: 0.3s;
  68. transform: translateX(160rpx);
  69. &.is-show {
  70. transform: translateX(-20px);
  71. }
  72. &-wrapper {
  73. @apply fixed z-50 overflow-visible;
  74. right: 0;
  75. }
  76. }
  77. </style>