PageSidebarBackToTop.vue 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <template>
  2. <transition name="fade">
  3. <svg
  4. v-if="show"
  5. class="go-to-top"
  6. xmlns="http://www.w3.org/2000/svg"
  7. viewBox="0 0 49.484 28.284"
  8. @click="scrollToTop"
  9. >
  10. <g transform="translate(-229 -126.358)">
  11. <rect
  12. fill="currentColor"
  13. width="35"
  14. height="5"
  15. rx="2"
  16. transform="translate(229 151.107) rotate(-45)"
  17. />
  18. <rect
  19. fill="currentColor"
  20. width="35"
  21. height="5"
  22. rx="2"
  23. transform="translate(274.949 154.642) rotate(-135)"
  24. />
  25. </g>
  26. </svg>
  27. </transition>
  28. </template>
  29. <script>
  30. import debounce from 'lodash.debounce'
  31. export default {
  32. name: 'BackToTop',
  33. props: {
  34. threshold: {
  35. type: Number,
  36. default: 300
  37. }
  38. },
  39. data () {
  40. return {
  41. scrollTop: null
  42. }
  43. },
  44. computed: {
  45. show () {
  46. return this.scrollTop > this.threshold
  47. }
  48. },
  49. mounted () {
  50. this.scrollTop = this.getScrollTop()
  51. window.addEventListener('scroll', debounce(() => {
  52. this.scrollTop = this.getScrollTop()
  53. }, 100))
  54. },
  55. methods: {
  56. getScrollTop () {
  57. return window.pageYOffset
  58. || document.documentElement.scrollTop
  59. || document.body.scrollTop || 0
  60. },
  61. scrollToTop () {
  62. window.scrollTo({ top: 0, behavior: 'smooth' })
  63. this.scrollTop = 0
  64. }
  65. }
  66. }
  67. </script>
  68. <style lang='stylus' scoped>
  69. .go-to-top {
  70. cursor: pointer;
  71. position: fixed;
  72. bottom: 1rem;
  73. right: .8rem;
  74. width: 2rem;
  75. color: #808080;
  76. z-index: 3;
  77. }
  78. .go-to-top:hover {
  79. color: lighten(#808080, 30%);
  80. }
  81. @media (max-width: 959px) {
  82. .go-to-top {
  83. display: none;
  84. }
  85. }
  86. .fade-enter-active, .fade-leave-active {
  87. transition: opacity 0.3s;
  88. }
  89. .fade-enter, .fade-leave-to {
  90. opacity: 0;
  91. }
  92. </style>