Vue 自定义ip地址输入组件
2023-12-28 04:10:06
实现效果:
组件代码
<template>
<div class="ip-input flex flex-space-between flex-center-cz">
<input type="text" v-model="value1" maxlength="3" ref="ip1" :placeholder="placeholder" @input="changeToNext1(value1)"/>
·
<input type="text" v-model="value2" maxlength="3" ref="ip2" :placeholder="placeholder" @input="changeToNext2(value2)"/>
·
<input type="text" v-model="value3" maxlength="3" ref="ip3" :placeholder="placeholder" @input="changeToNext3(value3)"/>
·
<input type="text" v-model="value4" maxlength="3" ref="ip4" :placeholder="placeholder" @input="ipAddress"/>
</div>
</template>
<script>
export default {
name:'IPInput',
props:{
placeholder:{},
ip: {}
},
model: {
prop: "ip",
event: "change"
},
created(){
},
watch:{
ip: {
handler(newVal) {
let arr = newVal.split(".")
if ( arr.length === 4 ) {
this.value1 = arr[0]
this.value2 = arr[1]
this.value3 = arr[2]
this.value4 = arr[3]
}
if ( newVal === "..." ) {
this.$emit("change", '')
}
},
deep: true
}
},
mounted() {
if (this.ip == null) return;
let arr = this.ip.split(".")
if ( arr.length === 4 ) {
this.value1 = arr[0]
this.value2 = arr[1]
this.value3 = arr[2]
this.value4 = arr[3]
this.$emit("change", this.value1 + "." + this.value2 + "." + this.value3 + "." + this.value4)
}
},
data() {
return {
value1: '',
value2: '',
value3: '',
value4: '',
}
},
methods:{
ipAddress() {
this.$emit("change", this.value1 + "." + this.value2 + "." + this.value3 + "." + this.value4);
},
changeToNext1(v) {
if (v.toString().length === 3) {
this.$nextTick(() => {
this.$refs.ip2.focus();
});
}
this.$emit("change", this.value1 + "." + this.value2 + "." + this.value3 + "." + this.value4);
},
changeToNext2(v) {
if (v.toString().length === 3) {
this.$nextTick(() => {
this.$refs.ip3.focus();
});
}
this.$emit("change", this.value1 + "." + this.value2 + "." + this.value3 + "." + this.value4);
},
changeToNext3(v) {
if (v.toString().length === 3) {
this.$nextTick(() => {
this.$refs.ip4.focus();
});
}
this.$emit("change", this.value1 + "." + this.value2 + "." + this.value3 + "." + this.value4);
}
}
}
</script>
<style scoped>
.ip-input {
box-sizing: border-box;
border: 1px solid #E1DCDC;
height: 28px;
background-color: #FFFFFF;
}
.ip-input input {
border: 0;
width: 100%;
text-align: center;
}
</style>
组件使用代码
<template>
<div class="root flex flex-col border-box padding-l">
<IpInput v-model="ip" style="width: 200px;"></IpInput>
</div>
</template>
<script>
import IpInput from '@/components/input/IpInput.vue'
export default{
name:'',
created() {
},
components: {IpInput},
data() {
return {
ip:null
}
},
methods:{
}
}
</script>
文章来源:https://blog.csdn.net/gdgztt/article/details/135257201
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!