在现代前端开发中,用户输入的格式化与验证是一个重要的任务。为了提升用户体验,我们可以通过自定义指令来限制用户在输入框内的输入。本文将介绍如何在 Vue 3 中实现一个名为 v-input
的自定义指令,用于处理不同类型的输入值,包括数字、数字加小数、数字加两位小数以及自定义规则。
一、指令概述
1. 指令功能
v-input
指令能处理以下输入类型:
- 数字:仅允许输入数字。
- 数字 + 小数:允许输入数字和小数点。
- 数字 + 两位小数:允许输入数字和最多两位小数。
- 自定义:通过
data-rule
属性提供的正则表达式来过滤输入值。
2. 使用示例
使用方式如下:
<input type="text" v-input:decimal_2="inputValue" data-rule="/^[0-9]+(\.[0-9]{1,2})?$/" />
在这个示例中,v-input:decimal_2
指定了输入类型为“数字 + 两位小数”,并且还提供了一个正则表达式作为自定义规则。
二、指令实现
接下来,我们来看如何实现这个指令。
1. 派发自定义事件
为了让 Vue 能够及时响应输入框的变化,我们需要触发一个输入事件:
const trigger = (el, type, options = {}) => {
if (!el || !type) {
throw new Error("Element and event type are required");
}
// 使用 Event 构造函数创建标准事件
let event = new Event(type, {
bubbles: true,
cancelable: true,
...options,
});
el.dispatchEvent(event);
};
2. 定义指令逻辑
指令的逻辑主要在 mounted
和 updated
钩子函数中实现。我们将根据不同的输入类型,处理输入框的值。
const inputDirective = {
mounted(el, binding) {
const _type = binding.arg;
const types = ["number", "decimal", "decimal_2", "customize"];
if (!_type || !types.includes(_type)) {
console.log(`使用v-input指令需要选择特定功能:v-input:type="inputValue"; type = ${types.join(' / "')}."`);
return;
}
el.$handler = (el) => {
let input = el.children[0].children[0];
switch (_type) {
// 数字
case "number":
input.value = input.value.replace(/[^\d]/, "");
break;
// 数字+小数
case "decimal":
input.value = input.value.replace(/[^\d.]/g, "");
input.value = input.value.replace(/\.{2,}/g, ".");
input.value = input.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
input.value.indexOf(".") < 0 && input.value !== "" && (input.value = parseFloat(input.value));
input.value.indexOf(".") > -1 && input.value.length === 1 && (input.value = "");
break;
// 数字+两位小数
case "decimal_2":
input.value = input.value.replace(/[^\d.]/g, "");
input.value = input.value.replace(/\.{2,}/g, ".");
input.value = input.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
input.value = input.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
input.value.indexOf(".") < 0 && input.value !== "" && (input.value = parseFloat(input.value));
input.value.indexOf(".") > -1 && input.value.length === 1 && (input.value = "");
break;
// 自定义
case "customize":
const rule = el.dataset.rule && eval(el.dataset.rule);
input.value = input.value.replace(rule, "");
break;
}
trigger(input, "input");
};
el.$handler(el);
},
updated(el) {
el.$handler && el.$handler(el);
},
};
export default inputDirective;
3. 处理不同输入类型的逻辑
在指令中,我们首先根据输入类型进行相应的处理:
- 数字:直接过滤非数字字符。
- 小数:允许输入数字和小数点,并确保小数点的使用符合规范。
- 两位小数:处理逻辑与小数相似,但限制小数位数为两位。
- 自定义:通过
data-rule
属性提供的正则表达式进行过滤。
三、使用指令
要在 Vue 应用中使用这个指令,您只需在组件中进行注册并在模板中调用它:
import inputDirective from './path/to/inputDirective';
export default {
directives: {
input: inputDirective
}
};
<template>
<div>
<input type="text" v-input:decimal_2="inputValue" data-rule="/^[0-9]+(\.[0-9]{1,2})?$/" />
</div>
</template>
四、总结
通过本篇文章,我们了解了如何在 Vue 3 中实现一个自定义输入处理指令 v-input
。这种指令不仅可以提高用户输入的准确性,还可以增强用户体验。希望本文对您在 Vue 开发中的指令使用有所帮助,鼓励您根据实际需求进行扩展和修改。