效果
使用
<template>
<IpInput ref="ipInput"></IpInput>
</template>
this.$refs.ipInput.getIP("10.90.15.66");
const ip = this.$refs.ipInput.value.getIP();
console.log(ip);
代码
<template>
<div v-for="(item, index) in ipAddress" :key="index" style="display: flex; width: 25%">
<el-input ref="ipInput" v-model="item.value" type="text" @input="checkFormat(item)" @keydown="setPosition(item, index, $event)" />
<div v-if="index < 3">.</div>
</div>
</template>
<script>
export default {
data() {
return {
ipAddress: [
{
value: ""
},
{
value: ""
},
{
value: ""
},
{
value: ""
}
]
};
},
methods: {
checkFormat(item) {
let val = item.value;
val = val.toString().replace(/[^0-9]/g, "");
val = parseInt(val, 10);
if (isNaN(val)) {
val = "";
} else {
val = val < 0 ? 0 : val;
val = val > 255 ? 255 : val;
}
item.value = val;
},
async setPosition(item, index, event) {
if (event && event.currentTarget.selectionStart !== event.currentTarget.selectionEnd) {
return;
}
if (event && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
event.preventDefault();
}
if (event.key === "ArrowLeft") {
if (event.currentTarget.selectionStart === 0) {
this.previousBlock(index);
} else {
event.currentTarget.selectionStart -= 1;
event.currentTarget.selectionEnd = event.currentTarget.selectionStart;
}
} else if (event.key === "ArrowRight") {
if (event.currentTarget.selectionStart === item.value.toString().length) {
this.nextBlock(index);
} else {
event.currentTarget.selectionStart += 1;
event.currentTarget.selectionEnd = event.currentTarget.selectionStart;
}
} else if (event.key === "Backspace") {
if ( event.currentTarget.selectionStart === 0) {
this.previousBlock(index);
}
} else if (event.key === "Enter" || event.key === "." || event.key === " ") {
this.nextBlock(index);
} else if (item.value.toString().length === 3 && event.currentTarget.selectionStart === 3) {
this.nextBlock(index);
}
},
nextBlock(index) {
if (index < 3) {
const element = this.$refs.ipInput[index + 1];
element.$el.querySelector(".el-input__inner").selectionStart = 0;
element.$el.querySelector(".el-input__inner").selectionEnd = 0;
element.focus();
}
},
previousBlock(index) {
if (index > 0) {
const element = this.$refs.ipInput[index - 1];
const position = this.ipAddress[index - 1]?.value?.toString().length;
element.$el.querySelector(".el-input__inner").selectionStart = position;
element.$el.querySelector(".el-input__inner").selectionEnd = position;
element.focus();
}
},
setIP(ip) {
const values = ip.split(".");
for (const i in this.ipAddress) {
this.ipAddress[i].value = values[i] ?? "";
}
},
getIP() {
let result = "";
for (const i in this.ipAddress) {
if (i > 0) result += ".";
result += this.ipAddress[i].value;
}
return result;
}
}
};
</script>