Vue实现回到顶部

新建一个Top组件

 1  2 <template>
 3     <div id="goTop">
 4         <div class="goTop" v-show="goTopShow" @click="goTop">
 5             <i class="el-icon-caret-top goTopIcon"></i>
 6             回到顶部
 7         </div>
 8     </div>
 9 </template>
10 <script>
11 export default {
12     name: "goTop",
13     data() {
14         return {
15             scrollTop: "",
16             goTopShow: false
17         };
18     },
19     watch: {
20         scrollTop(val) {
21             if (this.scrollTop > 500) {
22                 this.goTopShow = true;
23             } else {
24                 this.goTopShow = false;
25             }
26         }
27     },
28     methods: {
29         handleScroll() {
30             this.scrollTop =
31                 window.pageYOffset ||
32                 document.documentElement.scrollTop ||
33                 document.body.scrollTop;
34             if (this.scrollTop > 500) {
35                 this.goTopShow = true;
36             }
37         },
38         goTop() {
39             let timer = null,
40                 _that = this;
41             cancelAnimationFrame(timer);
42             timer = requestAnimationFrame(function fn() {
43                 if (_that.scrollTop > 0) {
44                     _that.scrollTop -= 250;
45                     document.body.scrollTop = document.documentElement.scrollTop =
46                         _that.scrollTop;
47                     timer = requestAnimationFrame(fn);
48                 } else {
49                     cancelAnimationFrame(timer);
50                     _that.goTopShow = false;
51                 }
52             });
53         }
54     },
55     mounted() {
56         window.addEventListener("scroll", this.handleScroll);
57     },
58     destroyed() {
59         window.removeEventListener("scroll", this.handleScroll);
60     }
61 };
62 </script>
63  
64 <style scoped>
65 .goTop {
66     position: fixed;
67     right: 40px;
68     bottom: 60px;
69      40px;
70     height: 40px;
71     border-radius: 50%;
72     background: #fff;
73     padding: 10px;
74     cursor: pointer;
75     box-shadow: 0 0 6px rgba(0, 0, 0, 0.12);
76 }
77 .goTop:hover .goTopIcon {
78     color: rgba(51, 153, 255, 1);
79 }
80 .goTopIcon {
81     font-size: 20px;
82     color: rgba(51, 153, 255, 0.8);
83 }
84 </style>
85  
86

在页面中使用(外层高度给高一点)

 <div id="app" style="height:2000px">
    <Top></Top>
  </div>
原文地址:https://www.cnblogs.com/z-j-c/p/12981994.html