封装一个返回顶部公共组件,多配置

有些时候,在列表中需要用到返回顶部按钮这样的功能,但是ui组件库的自己不喜欢,怎么自己实现一个呢?

html和css的样式结构 看起来非常简单。 下面看看核心的js代码

<template>
  <div class="content">
    //style样式为动态配置,src为动态配置 这样可以实现图片,样式,大小的自由控制
    <img v-show="showTopImg" :style="[myStyle]"  @click.stop="backTop" 
        :src="backIcon" class="backTop"
    >
  </div>
</template>



//css样式 默认position定位
<style lang="scss" scoped>
    .backTop{
      position: fixed;
    }
</style>

js控制部分,样式由父组件传递下来,没有取默认值

<script>
import icon from '@/assets/icon/backTop.png'
export default {
  data() {
    return {
      showTopImg: false, //控制按钮显示
      timer: null,
      timerId: null,
      scrollTop: 0 

    }
  },
  props: {
    // 触底显示返回高度,默认2500
    backHeight: {
      typeof: Number,
      default: 2500
    },
    // 父组件传下来的图片,没有取默认值
    backIcon: {
      typeof: String,
      default: icon
    },
    // 父组件传下来的样式,必须是对象,没有取默认值
    myStyle: {
      typeof: Object,
      default: () => {
        return {
          width: '66px',
          height: '66px',
          right: '10px',
          bottom: '68px'
        }
      }
    }
  },
  mounted() {
    //注册监听滚动事件
    window.addEventListener('scroll', this.debounce, true)
  },
  destroyed() {
    // 退出时清除监听事件
    window.removeEventListener('scroll', this.debounce)
    window.clearInterval(this.timerId)
    window.clearTimeout(this.timer)
  },
  methods: {
    backTop() {
      this.timerId = setInterval(() => {
        // 给返回增加动画效果
        const speed = Math.floor(-document.documentElement.scrollTop / 5)
        document.documentElement.scrollTop = document.documentElement.scrollTop + speed
        if (document.documentElement.scrollTop <= 0) {
          clearInterval(this.timerId)
        }
      }, 30)
    },
    // 防抖函数
    debounce(ev) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        // 当滚动的距离大于时出现该按钮
        this.scrollTop = window.pageYOffset
        this.scrollTop > this.backHeight ? 
        this.showTopImg = true : this.showTopImg = false
      }, 200)
    }
  }
}
</script>

在父组件中引用

<template>
  <div class="content">
    //到一定距离显示出来
    <backTop :backHeight="2000" :icon="https://xxxx.com" :myStyle="style"/>
  </div>
</template>

<script>
import backTop from '@/components/backTop'
export default {
  name: 'demo',
  components: {  backTop },

  data() {
    return {
       style:{
          width:"80px",
          hieght:"80px",
          right:"20px",
          bottom:"50px",
          background-color:""
       {
    }
  },
  created() {},
  methods: {}
}
</script>

<style lang="scss" scoped>

</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值