需求:封装一个输入框组件
1.只能输入英文。
2.输入的小写英文自动转大写。
3.输入的全角特殊符号自动转半角特殊字符
效果图
代码
<script setup>
import { defineEmits, defineModel, defineProps } from "vue";
import { debounce } from "lodash";/*** 1.只能输入英文* 2.输入的小写英文自动转大写:使用 JavaScript 的 toUpperCase() 方法来转换。* 3.输入的全角特殊符号自动转半角特殊字符:这个也可以通过正则和替换的方式来处理* @type {EmitFn<(string)[]>}*/
const emits = defineEmits(["input", "blur"]);
const inputStyle = defineModel("inputStyle"); // 输入框自定义样式
const inputValue = defineModel();const props = defineProps({// 输入最大长度maxLength: {type: Number,default: 10000},// 是否禁用isDisabled: {type: Boolean,default: false},// 是否显示后缀isShowAppend: {type: Boolean,default: false}
});
// 提示语
const placeholderInput = defineModel("placeholderInput", {default: "请输入"
});// 处理输入的逻辑
const handleInput = debounce(val => {let newValue = val.trim();// 1. 允许中文符号和英文符号的输入// 这里我们允许常见的符号,如:·¥……()【】、;‘,。!@#$%^&*()_+{}|:"<>?~`.,;'\-=\[\]\\\/newValue = newValue.replace(/[^a-zA-Z·¥……()【】、;‘,。!@#$%^&*()_+{}|:"<>?~`.,;'\-=\[\]\\/!]/g,"");// 2. 小写字母自动转为大写newValue = newValue.toUpperCase();// 3. 全角字符转为半角字符newValue = newValue.replace(/[\uFF01-\uFF5E]/g, match =>String.fromCharCode(match.charCodeAt(0) - 0xfee0));// 4. 手动转换全角的【】为半角的[]newValue = newValue.replace(/【/g, "[").replace(/】/g, "]");inputValue.value = newValue; // 更新输入框的值emits("input", inputValue.value); // 发出 input 事件
}, 300);// 失去焦点事件
const onBlur = () => {emits("blur", inputValue.value);
};
</script><template><div class="custom_common_input"><el-inputv-model="inputValue"clearable:disabled="isDisabled":maxlength="maxLength":input-style="inputStyle":placeholder="placeholderInput"style="width: 100%"@input="handleInput"@blur="onBlur"><template v-if="isShowAppend" #append><slot name="append" /></template></el-input></div>
</template><style scoped lang="scss">
.custom_common_input {width: 100%;
}
</style>
使用方法
const value = ref("");<BasicInputEn v-model="value" />