当前位置:网站首页>Long press the button to execute the function

Long press the button to execute the function

2022-07-07 01:35:00 Ah Liu

stay utils Create under folder longPress.ts

import {
     DirectiveOptions } from 'vue';

const longPress: DirectiveOptions = {
    
  // bind: Call it once , The first time an instruction is bound to an element 
  // el: Element bound by instruction , Can be used for direct operation  DOM.
  // binding: An object . name: Instruction name ,value: Binding value of instruction 
  // vnode: Compile generated virtual nodes 
  bind: function (el, binding, vNode) {
    
    // el Namely dom
    if (typeof binding.value !== 'function') {
    
      // eslint-disable-next-line
      console.log('callback must be a function');
    }
    //  Defining variables 
    let pressTimer: any = null;
    //  Operation function 
    const handler = (e: Event) => {
    
      binding.value(e);
    };
    //  Create timer (1 The function is executed in seconds  )
    const start = (e: any) => {
    
      if (e.type === 'click') {
    
        return;
      }
      if (pressTimer === null) {
    
        pressTimer = setTimeout(() => {
    
          handler(e);
        }, 1000);
      }
    };
    //  Cancel the timer 
    const cancel = () => {
    
      if (pressTimer !== null) {
    
        clearTimeout(pressTimer);
        pressTimer = null;
      }
    };
    //  Add event listener 
    el.addEventListener('mousedown', start);
    //  Cancel the timer 
    el.addEventListener('click', cancel);
    el.addEventListener('mouseout', cancel);
  },
  //  Triggered when the value passed in is updated 
  componentUpdated (el: any, {
     value }) {
    
    el.$value = value;
  },
  //  When an instruction is unbound to an element , Remove event binding 
  unbind (el: any) {
    
    el.removeEventListener('click', el.handler);
  }
};

export default longPress;

Introduce and use in required documents
introduce

import longpress from '@/utils/longpress';

@Component({
    
  components: {
    
    
  },
  directives: {
    
    longpress
  }
})

Use

<basic-button
  v-longpress="handleLongMoveLeft"
  type="info"
  plain
  icon="el-icon-arrow-left"
  @click="moveLeft"
/>
原网站

版权声明
本文为[Ah Liu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207061802223815.html