Vue版Backtop组件

2,585 阅读2分钟

前言

最近受疫情影响,工作上并不是很忙。趁小空闲时间偷偷撸了个scroll返回顶部的组件Backtop,稍微补充了下内部的组件库。Backtop也不是什么特别常用的组件,就当是闲暇无事打发时间。

目录结构

├─ index.less
├─ index.vue
├─ index.js 

props设计

right: {            //元素距离右边的距离
    type: Number,
    default: 10
},
bottom: {           //元素距底部距离
    type: Number,
    default: 10
},
target: {           //触发滚动的对象
    type: String
},
visibilityHeight: {   //滚动高度达到此值才显示
    type: Number,
    default: 100
}

组件实现

1. 实现平滑滚动代码

// utils
/**
 * scroll滚动到指定位置
 * @param {*} scrollNum 
 * @param {*} target 
 */
export const scrollToTop = (scrollNum, target) => {
    target.scrollTo({
        top: scrollNum,
        behavior: "smooth"
    });
}

2. index.vue

<template>
  <transition name="fade">
    <div
      v-show="show"
      @click.stop="click"
      class="g7-Backtop"
      :style="{right:`${right}px`,bottom:`${bottom}px`}"
    >
      <slot></slot>
    </div>
  </transition>
</template>

<script>
import { scrollToTop } from "../../utils";
export default {
  name: "G-Backtop",
  props: {
    right: {            //元素距离右边的距离
      type: Number,
      default: 10
    },
    bottom: {           //元素距底部距离
      type: Number,
      default: 10
    },
    target: {           //触发滚动的对象
      type: String
    },
    visibilityHeight: {   //滚动高度达到此值才显示
      type: Number,
      default: 100
    }
  },
  data() {
    return {
      element: document.body,   //默认body节点
      show: false
    };
  },
  watch: {
    target() {
      //target变化,销毁之前监听的事件,并且重新初始化
      this.element.removeEventListener("scroll", this.scroll);
      this.init();
    }
  },
  methods: {
    scroll(e) {
      this.show = e.target.scrollTop > this.visibilityHeight;
    },
    init() {
      //初始化DOM节点,并且监听scroll事件
      if (this.target) {
        this.element = document.querySelector(this.target);
        if (!this.element) {
          throw new Error(`未找到${this.target}节点`);
        }
      }
      this.element.setAttribute("style", "scroll-behavior: smooth");
      this.element.addEventListener("scroll", this.scroll);
    },
    /**
     * 
     */
    click() {
      scrollToTop(0, this.element);
      this.$emit("on-click");
    }
  },
  mounted() {
    this.init();
  },
  destroyed() {
    //组件销毁,销毁掉监听的事件
    this.element.removeEventListener("scroll", this.scroll);
  }
};
</script>

样式就没必要贴代码了,不会的找百度吧。

效果

往期回顾

总结

本人水平有限,搬砖不易,不足之处请多指教!
各种各样的业务组件经过内部业务的打磨后,会慢慢整理共享给需要的人......