vue 中使用防抖函数组件

应用场景:表单点击提交,快速点击可提交多次

使用方法:

import '@/util/debounce.js'

<Debounce :time="500" events="click" :immediate="true">
  <button class="primaryButton" @click.prevent="submitForm()">保存</button>
</Debounce>

main.css加入新的样式
.primaryButton {
  margin: 10px;
  padding: 9px 15px;
  font-size: 12px;
  border-radius: 3px;
  color: #FFF;
  background-color: #409EFF;
  border: 1px solid #409EFF;
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  -webkit-appearance: none;
  text-align: center;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  outline: 0;
  -webkit-transition: .1s;
  transition: .1s;
  font-weight: 500;
  align-items: flex-start;
}
.primaryButton:hover{
  background-color: #66b1ff;
}
.primaryButton:active{
  background-color: #3a8ee6;
}

注意事项:

<el-button>组件会出现问题,所以用原生组件<button>替换

防抖组件实现代码:

import Vue from 'vue'

const debounce = (func, time, ctx, immediate) => {
  let timer
  const rtn = (...params) => {
    clearTimeout(timer)

    if (immediate) {
      let callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, time)
      if (callNow) func.apply(ctx, params)
    } else {
      timer = setTimeout(() => {
        func.apply(ctx, params)
      }, time)
    }
  }
  return rtn
}

Vue.component('Debounce', {
  abstract: true,
  props: ['time', 'events', 'immediate'],
  created() {
    this.eventKeys = this.events && this.events.split(',')
  },
  render() {
    const vnode = this.$slots.default[0]
    // 如果默认没有传 events,则对所有绑定事件加上防抖
    if (!this.eventKeys) {
      this.eventKeys = Object.keys(vnode.data.on)
    }

    this.eventKeys.forEach(key => {
      vnode.data.on[key] = debounce(
        vnode.data.on[key],
        this.time,
        vnode,
        this.immediate
      )
    })

    return vnode
  }
})

参考CSDN博客

博客地址:https://blog.csdn.net/userkang/article/details/90144101

发布了8 篇原创文章 · 获赞 0 · 访问量 267
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览