vue常用指令

// v-enterInt: 只能输入正整数
Vue.directive('enterInt', {
  inserted(el) {
    el.addEventListener('keypress',function(e){
      e = e || window.event;
      let charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode;
      let re = /\d/;
      if(!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey){
        if(e.preventDefault){
          e.preventDefault();
        }else{
          e.returnValue = false;
        }
      }
    });
  }
});

// v-enterFloatNumber: 只能输入正数(包含小数)
Vue.directive('enterFloatNumber', {
  inserted(el) {
    el.addEventListener('keypress',function(e){
      e = e || window.event;
      let charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode;
      let re = /\d/;
      if(charcode === 46){
        if(e.target.value.includes('.')){
          e.preventDefault();
        }
      }else if(!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey){
        if(e.preventDefault){
          e.preventDefault();
        }else{
          e.returnValue = false;
        }
      }
    });
  }
});


// v-enterNumber: 只能数字,去掉e,支持负值
Vue.directive('enterNumber', {
  inserted(el) {
    el.addEventListener('keypress',function(e){
      e = e || window.event;
      let charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode;
      if(charcode === 46){
        if(e.target.value.includes('.')){
          e.preventDefault();
        }
      }else if(charcode === 101){
        e.preventDefault();
      }
    });
  }
});



// v-enterMoney: 钱相关,保留两位
Vue.directive('enterMoney', {
  inserted(el) {
    el.addEventListener('keypress',function(e){
      e = e || window.event;
      let charcode = typeof e.charCode === 'number' ? e.charCode : e.keyCode;
      let re = /\d/;
      let splitValue = e.target.value.split('.');
      if(charcode === 46){
        if(e.target.value.includes('.')){
          e.preventDefault();
        }
      }else if(!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey){
        if(e.preventDefault){
          e.preventDefault();
        }else{
          e.returnValue = false;
        }
      } else if(splitValue[1] && splitValue[1].length > 1){
        e.preventDefault();
      }
    });
  }
});


Vue.directive('preventReClick', {
  bind(el, binding) {
    const time = binding.value || 2000;
    el.addEventListener('click', () => {
      if (!el.disabled) {
        el.disabled = true;
        el.style.cursor = 'no-drop';
        setTimeout(() => {
          el.disabled = false;
          el.style.cursor = 'pointer'
        }, time)
      }
    })
  }
});

你可能感兴趣的:(vue常用指令)