vue 实用指令

  1. 限制input 只允许输入正整数
    <input type="number" v-number-only >
    directives: {
            // 限制input 只允许输入正整数
            'number-only': {
              bind(el) {
                el.addEventListener('input', function() {
                  let val = this.value.replace(/[^\d]/g, '');
                  if (val === '') {
                    this.value = '';
                  } else {
                    val = val.replace(/^0+/, '') || '0';
                    this.value = val;
                  }
                    // 异步派发事件
                    setTimeout(() => {
                      const event = new Event('input', { bubbles: true });
                      this.dispatchEvent(event);
                    }, 0);
                });
              }
            }
          }

     

posted @ 2025-12-06 19:37  一丝心情  阅读(6)  评论(0)    收藏  举报