vue指令防抖

2019-10-30  本文已影响0人  Z丿Sir

创建一个debounce文件夹,一个index.js一个debounce.js

import Debounce from './debounce'
const install = function(Vue) {
  Vue.directive('Debounce', Debounce)
}
if (window.Vue) {
  window.Debounce = Debounce
  Vue.use(install); // eslint-disable-line
}
Debounce.install = install
export default Debounce

import { debounce } from '@/utils/index'

let debounceEle 
let debounceFn
export default {
  bind(el, { name, value, oldValue, expression, arg, modifiers }) {
    debounceEle = debounce(value, 500, true)
    debounceFn = function(e){
      if (e.keyCode === 13) {
        debounceEle()
      }
    }
    const {enter, click} = modifiers
    if (enter) {
      // 元素上绑定回车事件
      el.addEventListener('keydown', debounceFn, false)
    }
    if (click) {
      el.addEventListener('click', debounceEle, false)
    }
  },
  unbind(el, { modifiers }) {
    const {enter, click} = modifiers
    if (enter) {
      el.removeEventListener('keydown', debounceFn)
    }
    if (click) {
      el.removeEventListener('click', debounceEle)
    }
    debounceEle = null
  }
}

组件中使用

import debounce from "@/directive/debounce/index.js"
directives:{ debounce },
// DOM使用
 <el-button type="primary" v-debounce.click="()=>{queryList(1)}">查询</el-button>
// JS中使用
  mounted() {
    // todo 回车事件
    let _this = this;
    this.debounce = debounce(function(){
       _this.queryList(1)
    },500,false)
    document.onkeydown = function(e) {
        _this.debounce()
    };
  },
上一篇下一篇

猜你喜欢

热点阅读