IP 输入框组件
<template>
<ul class="ipAdress">
<li v-for="(item, index) in ipAdress" :key="index">
<el-input
class="lonbon-input"
type="text"
@input="checkIpVal(item, index)"
@keyup="turnIpPOS(item, index, $event)"
@blur="setDefaultVal(item, index)"
v-model="item.value"
ref="ipInput"
/>
<div v-if="index < 3" class="point"></div>
</li>
</ul>
</template>
<script>
export default {
props: {},
data() {
return {
ipAdress: [
{
value: "",
},
{
value: "",
},
{
value: "",
},
{
value: "",
},
],
}
},
computed: {},
created() {},
mounted() {},
watch: {},
methods: {
/**
* @description: 重置ip
* @Date: 2022-01-20 16:25:17
* @param {*}
* @return {*}
*/
reset() {
this.ipAdress.forEach((item) => {
this.$set(item, "value", "")
})
},
/**
* @description: 设置ip
* @Date: 2022-01-20 16:25:29
* @param {*} data 数组
* @return {*}
*/
setValue(data) {
this.ipAdress.forEach((item, index) => {
this.$set(item, "value", data[index] || "")
})
this.updateValue()
},
checkIpVal(item, index) {
let self = this
//确保每个值都处于0-255
let val = item.value
//当输入的是空格时,值赋为空
val = val.trim()
val = parseInt(val, 10)
if (isNaN(val)) {
val = ""
} else {
val = val < 0 ? 0 : val
val = val > 255 ? 255 : val
}
item.value = val
this.updateValue()
},
turnIpPOS(item, index, event) {
let self = this
let e = event || window.event
// console.log(index)
//删除键把当前数据删除完毕后会跳转到前一个input,左一不做任何处理
if (e.keyCode == 8) {
let val = item.value
console.log(val)
if (index == 0) {
} else if (val == "") {
self.$refs.ipInput[index - 1].focus()
}
}
//右箭头、回车键、空格键、冒号均向右跳转,右一不做任何措施
if (
e.keyCode == 39 ||
e.keyCode == 13 ||
e.keyCode == 32 ||
e.keyCode == 190 ||
e.keyCode == 110
) {
if (index == 3) {
} else {
self.$refs.ipInput[index + 1].focus()
}
}
},
setDefaultVal(item, index) {
//当input失去焦点,而ip没有赋值时,会自动赋值为0
let val = item.value
if (val == "") {
item.value = "0"
}
this.updateValue()
},
/**
* @description: 更新绑定值
* @Date: 2022-01-20 16:25:50
* @param {*}
* @return {*}
*/
updateValue() {
let ip = []
this.ipAdress.forEach((item) => {
ip.push(item.value)
})
this.$emit("input", ip.join("."))
},
},
components: {},
}
</script>
<style scoped lang="less">
.ipAdress {
width: 100%;
height: 36px;
display: flex;
align-items: center;
border: 2px solid #33457e;
border-radius: 6px;
padding: 0;
}
.ipAdress li {
position: relative;
height: 100%;
margin: 0;
width: 25%;
list-style: none;
float: left;
.point {
position: absolute;
width: 2px;
height: 2px;
background: #fff;
border-radius: 50%;
right: 0;
bottom: 5px;
}
}
.lonbon-input {
height: 100% !important;
float: left;
border: none;
/deep/.el-input__inner {
float: left;
height: 100% !important;
border: none !important;
border-radius: 0;
}
}
</style>