// 父组件 例: ip 传入 127.0.0.1
<IpInput v-model="ip"></IpInput>
// 子组件
<template>
<div class="ip">
<el-input v-model="ips[0]" placeholder="0" @input="e => onChangeHandle(e, 0)" ref="ip0"/><section></section>
<el-input v-model="ips[1]" placeholder="0" @input="e => onChangeHandle(e, 1)" ref="ip1"/><section></section>
<el-input v-model="ips[2]" placeholder="0" @input="e => onChangeHandle(e, 2)" ref="ip2"/><section></section>
<el-input v-model="ips[3]" placeholder="0" @input="e => onChangeHandle(e, 3)" ref="ip3"/>
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: () => ""
}
},
data() {
return {
ips: ["","","",""]
}
},
mounted() {
this.ips = this.value.split(".")
},
watch: {
value(n) {
this.ips = n.split(".")
if (this.ips.length < 4) {
let number = 4 - this.ips.length
for (let i = 0; i < number; i++) {
this.ips.push("")
}
} else {
this.ips = this.ips.slice(0,4)
}
}
},
methods: {
onChangeHandle(input, num) {
if (input !== "") {
if (typeof input == "number") {
input = input.toString()
}
if (input.split(".").length === 4) {
this.ips = input.split(".")
this.$emit("input", this.ips.toString().replaceAll(",", "."))
return
}
if (input.length === 4 && num < 3) {
this.$refs["ip" + num].blur()
this.$refs["ip" + (num + 1)].focus()
}
if (input.length === 3 && num < 3 && !isNaN(Number(input)) && Number(input) > 255) {
this.$refs["ip" + num].blur()
this.$refs["ip" + (num + 1)].focus()
}
// 正则表达式模式:只能输入数字,范围在0到255之间
var numberPattern = /^(0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5])$/;
if (!numberPattern.test(input)) {
this.ips[num] = this.ips[num].slice(0, input.length - 1)
return
}
}
if (input.length === 3 && num < 3) {
this.$refs["ip" + num].blur()
this.$refs["ip" + (num + 1)].focus()
} else if (input.length === 0 && num > 0) {
this.$refs["ip" + num].blur()
this.$refs["ip" + (num - 1)].focus()
}
this.$emit("input", this.ips.toString().replaceAll(",", "."))
}
}
}
</script>
<style lang="scss">
.ip {
display: flex;
align-items: baseline;
border: 1px solid #DCDFE6;
border-radius: 4px;
padding: 0 15px;
.el-input {
width: 24px;
margin: 0 2px;
}
section {
background: black;
border-radius: 50%;
width: 3px;
height: 3px;
margin: 0 2px;
}
.el-input__inner {
border: 0 !important;
padding: 0;
text-align: center;
}
}
</style>
用element封装一个ip输入框
于 2023-12-12 17:19:45 首次发布