ui-back-top.vue 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. <template>
  2. <view @tap="backToTop" class="u-back-top" :class="['u-back-top--mode--' + mode]" :style="[{
  3. bottom: bottom + 'rpx',
  4. right: right + 'rpx',
  5. borderRadius: mode == 'circle' ? '10000rpx' : '8rpx',
  6. zIndex: uZIndex,
  7. opacity: opacity
  8. }, customStyle]">
  9. </view>
  10. </template>
  11. <script>
  12. export default {
  13. name: 'ui-back-top',
  14. props: {
  15. // 返回顶部的形状,circle-圆形,square-方形
  16. mode: {
  17. type: String,
  18. default: 'circle'
  19. },
  20. // 自定义图标
  21. icon: {
  22. type: String,
  23. default: 'arrow-upward'
  24. },
  25. // 提示文字
  26. tips: {
  27. type: String,
  28. default: ''
  29. },
  30. // 返回顶部滚动时间
  31. duration: {
  32. type: [Number, String],
  33. default: 100
  34. },
  35. // 滚动距离
  36. scrollTop: {
  37. type: [Number, String],
  38. default: 0
  39. },
  40. // 距离顶部多少距离显示,单位rpx
  41. top: {
  42. type: [Number, String],
  43. default: 400
  44. },
  45. // 返回顶部按钮到底部的距离,单位rpx
  46. bottom: {
  47. type: [Number, String],
  48. default: 100
  49. },
  50. // 返回顶部按钮到右边的距离,单位rpx
  51. right: {
  52. type: [Number, String],
  53. default: 40
  54. },
  55. // 层级
  56. zIndex: {
  57. type: [Number, String],
  58. default: '9'
  59. },
  60. // 整个组件的样式
  61. customStyle: {
  62. type: Object,
  63. default () {
  64. return {}
  65. }
  66. }
  67. },
  68. watch: {
  69. showBackTop(nVal, oVal) {
  70. // 当组件的显示与隐藏状态发生跳变时,修改组件的层级和不透明度
  71. // 让组件有显示和消失的动画效果,如果用v-if控制组件状态,将无设置动画效果
  72. if (nVal) {
  73. this.uZIndex = this.zIndex;
  74. this.opacity = 1;
  75. } else {
  76. this.uZIndex = -1;
  77. this.opacity = 0;
  78. }
  79. }
  80. },
  81. computed: {
  82. showBackTop() {
  83. // 由于scrollTop为页面的滚动距离,默认为px单位,这里将用于传入的top(rpx)值
  84. // 转为px用于比较,如果滚动条到顶的距离大于设定的距离,就显示返回顶部的按钮
  85. return this.scrollTop > uni.upx2px(this.top);
  86. },
  87. },
  88. data() {
  89. return {
  90. // 不透明度,为了让组件有一个显示和隐藏的过渡动画
  91. opacity: 0,
  92. // 组件的z-index值,隐藏时设置为-1,就会看不到
  93. uZIndex: -1
  94. }
  95. },
  96. methods: {
  97. backToTop() {
  98. uni.pageScrollTo({
  99. scrollTop: 0,
  100. duration: this.duration
  101. });
  102. }
  103. }
  104. }
  105. </script>
  106. <style lang="scss" scoped>
  107. .u-back-top {
  108. width: 80rpx;
  109. height: 80rpx;
  110. position: fixed;
  111. z-index: 9;
  112. display: flex;
  113. flex-direction: column;
  114. justify-content: center;
  115. background: url(@/static/img/top.svg) rgba(0, 0, 0, 0.7) no-repeat center center;
  116. align-items: center;
  117. background-size: 80rpx;
  118. transition: opacity 0.4s;
  119. }
  120. </style>