需求:封裝一個輸入框組件
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" />