封装一下返回顶部吧,这个在实际开发中用到的地方很多,看一下具体实现代码吧
- 父页面引入注册子组件
<template>
<div class="home">
<Gotop/>
</div>
</template>
<script>
// @ is an alias to /src
import Gotop from "@/components/Gotop.vue";
export default {
name: "Home",
components: {
Gotop
}
};
</script>
- 子组件中写返回顶部的操作
<template>
<div id="top">
<p v-for="item in 200" :key="item">{{item}}</p>
<div @click="goTop" class="gotop">
<img class="img_gotop" width="30px" src="../../public/img/go_top.png" alt="">
</div>
</div>
</template>
<script>
export default {
data() {
return {};
},
created() {},
methods: {
//点击返回顶部
goTop() {
//创建一个计时器
var timer = setInterval(function() {
let osTop =
document.documentElement.scrollTop || document.body.scrollTop;
let ispeed = Math.floor(-osTop / 5);
document.documentElement.scrollTop = document.body.scrollTop =
osTop + ispeed;
console.log(osTop);
if (osTop === 0) {
clearInterval(timer);
}
}, 30);
}
}
};
</script>
<style scoped lang="scss">
#top {
width: 100%;
// border: 1px solid red;
p {
text-align: center;
}
.gotop {
width: 40px;
height: 40px;
bottom: 10%;
right: 5%;
border: 1px solid #eee;
position: fixed;
text-align: center;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
}
</style>
简单写一下自己的写法。希望对大家有帮助!