需求复现
某项目中,某模块要求限制输入框输入头尾空格,允许输入中间空格
注意事项
尾空格与中间空格需做区分,如果输入框直接限制空格的输入,则可以直接使用v-model.trim=''去限制空格输入,但这种方法会导致中间空格都无法输入,但是现需求需要支持中间空格的输入,所以需要对用户输入的空格判断是尾空格还是中间空格
具体实现
技术栈:Vue + Element-UI
前空格实现:
Vue.directive 创建全局自定义指令,并在该指令中使用正则表达式和 el-input
的 @input
监听方法,当第一个字符为空格即将其替换为空
尾空格实现:Vue.directive 创建全局自定义指令,并在该指令中使用正则表达式和 el-input
的 @change
方法,对于用户的输入值,在失焦时(change事件)进行判断,如果以空格结尾,则去除空格
<!-- 在 main.js 或其他入口文件中注册全局指令 --> import Vue from 'vue'; // 去除头空格 Vue.directive('no-head-space', { // bind 钩子函数会在指令绑定到元素时调用 bind(el, binding,vnode){ el.addEventListener('input', function(event) { const inputValue = event .target.value const trimmedValue = inputValue.trimLeft() if (inputValue !== trimmedValue) { event.target.value = trimmedValue event.target.dispatchEvent(new Event('input', { bubbles: true })) } }) } }) // 去除尾空格 Vue.directive('no-tail-space', { // bind 钩子函数会在指令绑定到元素时调用 bind(el, binding, vnode) { // 绑定 @input 监听方法 el.addEventListener('change', function (event) { // 获取输入的值 const value = event.target.value; // 使用正则表达式检测后空格 const regex = /\s+$/; // 如果输入值以空格结尾,失去焦点时,则替换为空 if (regex.test(value)) { // 使用 replace 方法替换反斜杠为空格 const newValue = value.replace(regex, ''); // 将新值设置回输入框 event.target.value = newValue; // 触发 @input 事件,使其更新组件中的数据 vnode.componentInstance.$emit('input', newValue); } }); }, }); // 在组件的模板中使用指令 <template> <el-input v-no-head-space v-no-tail-space v-model="inputValue"></el-input> </template> <script> export default { data() { return { inputValue: '', }; }, }; </script>
注:个人学习记录,如有不对的地方,欢迎各位佬指出。若有侵权,私信删。