Vue IP地址输入框实例代码

 更新时间:2023年10月26日 14:40:21   作者:Krpgly  
本文通过实例代码给大家介绍Vue IP地址输入框实现,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

Vue IP地址输入框

效果

使用

<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: ""
        }
      ]
    };
  },
  // 开启实时更新并emit IP地址
  // watch: {
  //   ipAddress: {
  //     // 双向数据绑定的value
  //     handler: function () {
  //       this.$emit("changed", this.getIP());
  //     },
  //     deep: true
  //   }
  // },
  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 (/* item.value.toString() === "" && */ 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) {
        // 输入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>

补充:Vue3实现IP地址输入框

前言

在网上找了一点资料,但是还是觉得不太行,就自己写了一个,与网上的也大差不差,都是用4个输入框和.号组合起来的,主要就是监听输入框事件和键盘按下事件还有光标位置完成的,废话不多说,直接复制就可以用了。

使用方法

1.我已经将这个代码注册为了一个组件,在自己的组件库中创建文件IpModel.vue,将下面的代码复制到组件中。

#IpModel.vue
<template>
  <div class="ip-input">
    <input id="ip1" v-model="ip1" ref='input1' @input="handleInput(1)" @keydown="handleKeyDown($event, 1)"
      maxlength="3" />
    <span>.</span>
    <input id="ip2" v-model="ip2" ref='input2' @input="handleInput(2)" @keydown="handleKeyDown($event, 2)"
      maxlength="3" />
    <span>.</span>
    <input id="ip3" v-model="ip3" ref='input3' @input="handleInput(3)" @keydown="handleKeyDown($event, 3)"
      maxlength="3" />
    <span>.</span>
    <input id="ip4" v-model="ip4" ref='input4' @input="handleInput(4)" @keydown="handleKeyDown($event, 4)"
      maxlength="3" />
  </div>
</template>
 
<script>
export default {
  name: "IpModel",
  props: {
    IP: String,
  },
  data() {
    return {
      ip1: "",
      ip2: "",
      ip3: "",
      ip4: "",
    };
  },
  methods: {
    handleInput(index) {
      this[`ip${index}`] = this[`ip${index}`].replace(/[^0-9]/g, '')
      let ip = this[`ip${index}`];
      if (ip.length > 1 && ip[0] === "0") {
        this[`ip${index}`] = ip.slice(1);
      }
      if (ip > 255) {
        this[`ip${index}`] = "255";
      }
      if (ip.length === 3 || ip[0] === "0") {
        let nextIndex = index + 1;
        if (nextIndex <= 4) {
          this.$refs[`input${nextIndex}`].focus();
        }
      }
    },
    handleKeyDown(event, index) {
      let ip = this[`ip${index}`];
      if (event.keyCode == 8 && 0 == document.getElementById(`ip${index}`).selectionStart) {
        let nextIndex = index - 1;
        if (nextIndex >= 1) {
          this.$refs[`input${nextIndex}`].focus();
          document.getElementById(`ip${nextIndex}`).setSelectionRange(this[`ip${nextIndex}`].length, this[`ip${nextIndex}`].length)
        }
      } else if (event.keyCode == 46 && ip.length == document.getElementById(`ip${index}`).selectionStart) {
        let nextIndex = index + 1;
        if (nextIndex <= 4) {
          this.$refs[`input${nextIndex}`].focus();
          document.getElementById(`ip${nextIndex}`).setSelectionRange(0, 0)
        }
      }
      else if ((event.keyCode == 37) && 0 == document.getElementById(`ip${index}`).selectionStart) {
        let nextIndex = index - 1;
        if (nextIndex >= 1) {
          this.$refs[`input${nextIndex}`].focus();
          document.getElementById(`ip${nextIndex}`).setSelectionRange(this[`ip${nextIndex}`].length, this[`ip${nextIndex}`].length)
        }
      } else if ((event.keyCode == 39) && ip.length == document.getElementById(`ip${index}`).selectionStart) {
        let nextIndex = index + 1;
        if (nextIndex <= 4) {
          this.$refs[`input${nextIndex}`].focus();
          document.getElementById(`ip${nextIndex}`).setSelectionRange(0, 0)
        }
      } else if (event.keyCode == 110 || event.keyCode == 190) {
        let nextIndex = index + 1;
        if (nextIndex <= 4) {
          this.$refs[`input${nextIndex}`].focus();
        }
      } else {
        return false
      }
    },
    IpModelSend() {
      if (this.ip1 == '' || this.ip2 == '' || this.ip3 == '' || this.ip4 == '') {
        this.$message({
          duration: 1000,
          message: 'IP地址非法,请输入正确的IP地址!'
        });
      } else {
        const ip = this.ip1 + '.' + this.ip2 + '.' + this.ip3 + '.' + this.ip4
        this.$emit('changeIP', ip);
      }
    },
    IpModelCancel() {
      this.ip1 = this.IP.split('.')[0]
      this.ip2 = this.IP.split('.')[1]
      this.ip3 = this.IP.split('.')[2]
      this.ip4 = this.IP.split('.')[3]
    }
  },
};
</script>
 
<style scoped>
.ip-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 160px;
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 0 10px;
  box-sizing: border-box;
  font-size: 16px;
}
 
.ip-input input {
  width: 30px;
  height: 90%;
  border: none;
  outline: none;
  text-align: center;
  font-size: 16px;
}
 
.ip-input span {
  font-size: 16px;
}
</style>

2.在需要使用到IP输入框的地方调用组件即可,例如:

<template>
  <div>
    <button class="ethernet" @click="IPVisible = true">IP输入框</button>
    <el-dialog v-model="IPVisible" title="" width="350px" align-center>
      <IpModel ref="ipModel" :IP="IP" v-on:changeIP="changeIP"></IpModel>
      <template #footer>
        <el-button @click="ipModelSure">确认</el-button>
        <el-button @click="ipModelCancel">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
 
<script>
import IpModel from '../components/IpModel.vue'
export default {
  components: {
    IpModel
  },
  data() {
    return {
      IPVisible: false,
      IP: "127.0.0.1",
    }
  },
  methods: {
    ipModelSure() {
      this.$refs.ipModel.IpModelSend(); // 调用IpModel子组件的IpModelSend方法
    },
    ipModelCancel() {
      this.IPVisible = false
      this.$refs.ipModel.IpModelCancel(); // 调用IpModel子组件的IpModelCancel方法
    },
    changeIP(value) {
      console.log(value)
      this.IPVisible = false
    },
  },
}
</script>
 
<style scoped></style>

3.当点击确定按钮时,父组件通过this.$refs.ipModel.IpModelSend();去调用子组件的方法,子组件通过this.$emit('changeIP', ip);返回ip值,父组件通过监听事件changeIP调用方法打印出ip

4.当点击取消按钮时,父组件通过this.$refs.ipModel.IpModelCancel();去调用子组件的方法,重新给ip赋值,使数据不产生变化

到此这篇关于Vue IP地址输入框的文章就介绍到这了,更多相关vue ip地址输入框内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • vue 组件 全局注册和局部注册的实现

    vue 组件 全局注册和局部注册的实现

    下面小编就为大家分享一篇vue 组件 全局注册和局部注册的实现,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-02-02
  • Vue2 使用 Echarts 创建图表实例代码

    Vue2 使用 Echarts 创建图表实例代码

    本篇文章主要介绍了Vue2 使用 Echarts 创建图表实例代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • vue限制实现不登录无法进入其他页面

    vue限制实现不登录无法进入其他页面

    本文主要介绍了vue限制实现不登录无法进入其他页面,vue限制不登录,通过url进入其他页面强制回到登录页面;已经登录的情况下,不可以再进入登录界面,感兴趣的可以了解一下
    2024-01-01
  • el-select如何获取下拉框选中label和value的值

    el-select如何获取下拉框选中label和value的值

    在开发业务场景中我们通常遇到一些奇怪的需求,例如el-select业务场景需要同时获取我们选中的label跟 value,下面这篇文章主要给大家介绍了关于el-select如何获取下拉框选中label和value的值,需要的朋友可以参考下
    2022-10-10
  • vue.js组件之间传递数据的方法

    vue.js组件之间传递数据的方法

    本篇文章主要介绍了vue.js组件之间传递数据的方法,组件实例的作用域是相互独立的,如何传递数据也成了组件的重要知识点之一,有兴趣的可以了解一下
    2017-07-07
  • Vue中使用 setTimeout() setInterval()函数的问题

    Vue中使用 setTimeout() setInterval()函数的问题

    这篇文章主要介绍了Vue中使用 setTimeout() setInterval()函数的问题 ,需要的朋友可以参考下
    2018-09-09
  • element el-input directive数字进行控制

    element el-input directive数字进行控制

    本文介绍了vue使用directive 进行控制的方法,使用element开发的过程中遇到循环的数据只能输入数字,并且有不要小数点,有需要小数点的,就有一定的参考价值,有兴趣的可以了解一下
    2018-10-10
  • Vue Element前端应用开发之常规Element界面组件

    Vue Element前端应用开发之常规Element界面组件

    在我们开发BS页面的时候,往往需要了解常规界面组件的使用,小到最普通的单文本输入框、多文本框、下拉列表,以及按钮、图片展示、弹出对话框、表单处理、条码二维码等等,本篇随笔基于普通表格业务的展示录入的场景介绍这些常规Element组件的使用
    2021-05-05
  • Vue项目之ES6装饰器在项目实战中的应用

    Vue项目之ES6装饰器在项目实战中的应用

    作为一个曾经的Java coder,当第一次看到js里面的装饰器Decorator,就马上想到了Java中的注解,当然在实际原理和功能上面,Java的注解和js的装饰器还是有很大差别的,这篇文章主要给大家介绍了关于Vue项目之ES6装饰器在项目实战中应用的相关资料,需要的朋友可以参考下
    2022-06-06
  • Vue中import与@import的区别及使用场景说明

    Vue中import与@import的区别及使用场景说明

    这篇文章主要介绍了Vue中import与@import的区别及使用场景说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06

最新评论