vue 注册自定义指令,对输入框输入内容过滤(区分中英文)

注册vue全局指令

对el-input输入框进行最大长度过滤(区分中英文)

过滤空格

注册全局指令

main.js

javascript 复制代码
/**
 * 输入框最长输入限制
 * @param {*} e 文本内容
 * @param {number} maxlength 最大字符长度
 * @param {boolean} trim 是否过滤空格
 * @returns {string} 最终文本
 */
const checkLength = (e, maxlength, trim) => {
  let b = 0; // 输入的字符数
  let r = String(e);//过滤掉所有空格
  if (trim) {
    r = String(e).replace(/\s+/g, "")
  }
  const reg = /^[\u0000-\u00ff]$/; //排除汉字和中文字符
  const len = r.length
  for (let i = 0; i < len; i++) {
    let c = r.charAt(i);
    if (reg.test(c)) {
      b++;
    } else {
      b += 2;
    }
    if (b > maxlength) { // 字符长度限制
      r = r.substr(0, i);
      break;
    }
  }
  return r
};

// 自定义指令-输入文本过滤
Vue.directive('limit-input', {
  bind(el, bindings, vnode) {
    const maxlength = typeof(bindings.value)=='object'
      ?bindings.value.maxlength
      :bindings.value;
    const trim = typeof(bindings.value)=='object'
      ?bindings.value.trim
      :false;
      
    el.addEventListener('input', (e) => {
      e.target.value = checkLength(e.target.value, maxlength, trim);
    });
  }
});

使用

test.vue

html 复制代码
<template>
	<div>
    <el-input
      clearable
      v-limit-input="{
        maxlength: 100,
        trim: true,
      }"
    ></el-input>

    <el-input
      type="textarea"
      v-limit-input="{
        maxlength: 400,
        trim: false,
      }"
    ></el-input>
  </div>
</template>
相关推荐
yuanyxh2 小时前
macOS 应用 - 纯对话生成
前端·macos·ai编程
大家的林语冰2 小时前
ES5 凉凉,Babel 8 正式发布,默认不再编译为 ES5 和 CJS......
前端·javascript·前端工程化
光影少年3 小时前
react批量更新、同步/异步更新场景
前端·react.js·掘金·金石计划
假如让我当三天老蒯3 小时前
模块化:ES Module 与 CommonJS 的区别
前端·面试
用户40950115773173 小时前
Private Forge v2.0 发布:12大前端业务场景技能系统
前端
weedsfly4 小时前
异步编程全景与事件循环——彻底搞懂 JS 执行机制
前端·javascript
用户059540174464 小时前
AI Agent记忆测试踩坑实录:Mock骗了我一周,Mem0+pytest一招破局
前端·css
用户1733598075374 小时前
纯前端 PDF 数字签名实战:Vue 3 + pdf-lib 在浏览器里完成签名嵌入
前端·javascript
IT_陈寒5 小时前
SpringBoot自动配置的坑,我爬了三天才出来
前端·人工智能·后端
Avan_菜菜12 小时前
AI 能写代码了,为什么我反而开始要求它先写文档?
前端·github·ai编程