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赋值,使数据不产生变化

结束

伍鳴
2023/3/23 发布

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现一个自定义的IP地址输入框,可以借助WPF的自定义控件来实现。以下是一个简单的实现步骤: 1. 创建一个新的WPF自定义控件,并命名为"IPAddressInputBox"。 2. 在控件的XAML文件中,添加四个文本框用于输入IP地址的四个部分,以及用于分隔符的文本标签。 3. 在控件的代码文件中,添加四个依赖属性,分别对应IP地址的四个部分,以及一个绑定整个IP地址的依赖属性。 4. 在控件的代码文件中,添加一个IP地址验证方法,用于检查输入的IP地址是否合法。 5. 在控件的代码文件中,添加一个值改变事件,当任何一个IP地址部分的值发生改变时,验证IP地址的合法性,并更新绑定整个IP地址的依赖属性。 下面是一份示例代码,实现了一个简单的自定义IP地址输入框IPAddressInputBox.xaml: ```xaml <UserControl x:Class="WpfCustomControls.IPAddressInputBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid> <TextBox x:Name="txtBox1" Width="40" MaxLength="3" TextChanged="txtBox_TextChanged"/> <TextBlock Text="." Margin="5,0,5,0"/> <TextBox x:Name="txtBox2" Width="40" MaxLength="3" TextChanged="txtBox_TextChanged"/> <TextBlock Text="." Margin="5,0,5,0"/> <TextBox x:Name="txtBox3" Width="40" MaxLength="3" TextChanged="txtBox_TextChanged"/> <TextBlock Text="." Margin="5,0,5,0"/> <TextBox x:Name="txtBox4" Width="40" MaxLength="3" TextChanged="txtBox_TextChanged"/> </Grid> </UserControl> ``` IPAddressInputBox.xaml.cs: ```csharp using System.Windows; using System.Windows.Controls; namespace WpfCustomControls { public partial class IPAddressInputBox : UserControl { public static readonly DependencyProperty IP1Property = DependencyProperty.Register("IP1", typeof(string), typeof(IPAddressInputBox), new PropertyMetadata("", OnIPChanged)); public static readonly DependencyProperty IP2Property = DependencyProperty.Register("IP2", typeof(string), typeof(IPAddressInputBox), new PropertyMetadata("", OnIPChanged)); public static readonly DependencyProperty IP3Property = DependencyProperty.Register("IP3", typeof(string), typeof(IPAddressInputBox), new PropertyMetadata("", OnIPChanged)); public static readonly DependencyProperty IP4Property = DependencyProperty.Register("IP4", typeof(string), typeof(IPAddressInputBox), new PropertyMetadata("", OnIPChanged)); public static readonly DependencyProperty IPAddressProperty = DependencyProperty.Register("IPAddress", typeof(string), typeof(IPAddressInputBox), new PropertyMetadata("", OnIPAddressChanged)); public string IP1 { get { return (string)GetValue(IP1Property); } set { SetValue(IP1Property, value); } } public string IP2 { get { return (string)GetValue(IP2Property); } set { SetValue(IP2Property, value); } } public string IP3 { get { return (string)GetValue(IP3Property); } set { SetValue(IP3Property, value); } } public string IP4 { get { return (string)GetValue(IP4Property); } set { SetValue(IP4Property, value); } } public string IPAddress { get { return (string)GetValue(IPAddressProperty); } set { SetValue(IPAddressProperty, value); } } public IPAddressInputBox() { InitializeComponent(); } private static void OnIPChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var inputBox = (IPAddressInputBox)d; inputBox.IPAddress = string.Format("{0}.{1}.{2}.{3}", inputBox.IP1, inputBox.IP2, inputBox.IP3, inputBox.IP4); } private static void OnIPAddressChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var inputBox = (IPAddressInputBox)d; var parts = inputBox.IPAddress.Split('.'); if (parts.Length == 4) { inputBox.IP1 = parts[0]; inputBox.IP2 = parts[1]; inputBox.IP3 = parts[2]; inputBox.IP4 = parts[3]; } } private void txtBox_TextChanged(object sender, TextChangedEventArgs e) { var tb = sender as TextBox; if (tb != null) { var value = tb.Text; if (string.IsNullOrEmpty(value) || int.TryParse(value, out int result) && result >= 0 && result <= 255) { // Value is valid tb.Foreground = SystemColors.WindowTextBrush; OnIPChanged(this, null); } else { // Value is invalid tb.Foreground = Brushes.Red; } } } } } ``` 使用自定义控件时,可以在XAML中引用,并绑定其依赖属性: ```xaml <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:custom="clr-namespace:WpfCustomControls;assembly=WpfCustomControls" Title="MainWindow" Height="450" Width="800"> <Grid> <custom:IPAddressInputBox IPAddress="{Binding MyIPAddress}" /> </Grid> </Window> ``` 其中,"MyIPAddress"是一个ViewModel中的属性,用于绑定整个IP地址的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值