UNPKG

1.83 kBPlain TextView Raw
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
30<script>
31import debounce from 'lodash.debounce'
32
33export default {
34 name: 'BackToTop',
35
36 props: {
37 threshold: {
38 type: Number,
39 default: 300
40 }
41 },
42
43 data () {
44 return {
45 scrollTop: null
46 }
47 },
48
49 computed: {
50 show () {
51 return this.scrollTop > this.threshold
52 }
53 },
54
55 mounted () {
56 this.scrollTop = this.getScrollTop()
57 window.addEventListener('scroll', debounce(() => {
58 this.scrollTop = this.getScrollTop()
59 }, 100))
60 },
61
62 methods: {
63 getScrollTop () {
64 return window.pageYOffset
65 || document.documentElement.scrollTop
66 || document.body.scrollTop || 0
67 },
68
69 scrollToTop () {
70 window.scrollTo({ top: 0, behavior: 'smooth' })
71 this.scrollTop = 0
72 }
73 }
74}
75</script>
76
77<style lang='stylus' scoped>
78.go-to-top {
79 cursor: pointer;
80 position: fixed;
81 bottom: 2rem;
82 right: 2.5rem;
83 width: 2rem;
84 color: $accentColor;
85 z-index: 1;
86}
87
88.go-to-top:hover {
89 color: lighten($accentColor, 30%);
90}
91
92@media (max-width: 959px) {
93 .go-to-top {
94 display: none;
95 }
96}
97
98.fade-enter-active, .fade-leave-active {
99 transition: opacity 0.3s;
100}
101
102.fade-enter, .fade-leave-to {
103 opacity: 0;
104}
105</style>