限制条件:
1.文本框只能输入数字
2.可以通过点选输入中文和括号
3.光标可以移动,且点选输入的要到当前光标处
代码:
<template v-for="logicSymbol in logicSymbols">
<el-button
type="blue"
size="small"
:key="`${logicSymbol.itemCode}`"
@click="HandelClick(logicSymbol.itemName)"
>{{ logicSymbol.itemName }}</el-button
>
</template>
<el-input
@blur="handleInputBlur"
v-model="conditionExpressionData"
type="text"
clearable
placeholder="条件表达式"
ref="inputArea"
oninput="value=value.replace(/[^0-9且或()]/g, '')" // 直接在输入后把不合法的字符替换掉。这个方法即可
//@keypress.native="handleKeyPress" // 第二种方式,在键盘输入的时候控制不让某些键输入
/>
// data
conditionExpressionData: "",
cursorIndex: null,
logicSymbols: [
{
itemName: "且",
itemCode: "and",
},
{
itemName: "或",
itemCode: "or",
},
{
itemName: "(",
itemCode: "(",
},
{
itemName: ")",
itemCode: ")",
},
],
// methods
// 获取光标插入文本
insertStr(soure, start, newStr) {
if(start===null){
return soure+newStr
}else{
return soure.slice(0, start) + newStr + soure.slice(start);
}
},
// 控制点选
HandelClick(str) {
this.conditionExpressionData = this.insertStr(
this.conditionExpressionData,
this.cursorIndex,
str
);
this.$refs.inputArea.focus();
// console.log(this.cursorIndex);
},
// blur事件
handleInputBlur(e) {
this.cursorIndex = e.srcElement.selectionStart;
// input 方法后,要重新赋值
this.conditionExpressionData = e.target.value
},
// 键盘点击事件 控制键盘某些键可以点击。但是限制不了中文。所以最好用input的方式
handleKeyPress(e) {
let keyCode = e.keyCode;
if ((keyCode >= 48 && keyCode <= 57) || keyCode == 8) {
e.returnValue = true;
} else {
e.returnValue = false;
}
},