美文网首页
vue指令防抖

vue指令防抖

作者: Z丿Sir | 来源:发表于2019-10-30 11:49 被阅读0次

    创建一个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()
        };
      },
    

    相关文章

      网友评论

          本文标题:vue指令防抖

          本文链接:https://www.haomeiwen.com/subject/nprovctx.html