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>
相关推荐
YAY_tyy1 分钟前
数据处理:要素裁剪、合并与简化
前端·arcgis·turfjs
LYFlied11 分钟前
【每日算法】LeetCode 62. 不同路径(多维动态规划)
前端·数据结构·算法·leetcode·动态规划
console.log('npc')28 分钟前
vue3文件上传弹窗,图片pdf,word,结合预览kkview
前端·javascript·vue.js·pdf·word
inferno34 分钟前
CSS 基础(第二部分)
前端·css
BD_Marathon37 分钟前
Router_路由传参
前端·javascript·vue.js
闲云一鹤44 分钟前
Cesium 去掉默认瓦片和地形,解决网络不好时地图加载缓慢的问题
前端·cesium
Dreamcatcher_AC1 小时前
前端面试高频13问
前端·javascript·vue.js
AI陪跑1 小时前
深入剖析:GrapesJS 中 addStyle() 导致拖放失效的问题
前端·javascript·react.js
登山人在路上1 小时前
Vue中导出和导入
前端·javascript·vue.js
消失的旧时光-19431 小时前
Flutter 路由从 Navigator 到 go_router:嵌套路由 / 登录守卫 / 深链一次讲透
前端·javascript·网络