封装返回顶部组件

本文介绍了如何在 Vue.js 项目中封装一个返回顶部的组件,该组件在实际开发中应用广泛。通过在父页面引入并注册子组件,然后在子组件内编写实现返回顶部功能的代码,实现了一个简单的返回顶部操作。希望能对开发者提供帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

封装一下返回顶部吧,这个在实际开发中用到的地方很多,看一下具体实现代码吧

  • 父页面引入注册子组件
<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>

简单写一下自己的写法。希望对大家有帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值