Vue数字输入框组件使用方法详解

前面的话

关于基础组件介绍,已经更新完了。这篇文章将用组件基础知识开发一个数字输入框组件。将涉及到指令、事件、组件间通信。

基础需求

  • 只能输入数字
  • 设置初始值,最大值,最小值
  • 在输入框聚焦时,增加对键盘上下键的支持
  • 增加一个控制步伐prop-step,例如,设置为10 ,点击加号按钮,一次增加10

项目搭建

在了解需求后,进行项目的初始化:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <div id="app">
 <input-number></input-number>
 </div>
</body>
</html>
<script>
 Vue.component('input-number',{
 template: `
  <div class="input-number">
  <input type="text" />
  <button>-</button>
  <button>+</button>
  </div>
 `}
 var app = new Vue({
 el:'#app'
 })
</script>

初始化结构搭好后,由于要设置初始值,最大值、最小值,我们在父组件中的 < input-number>< /input-number>上设置这些值,并且通过Props将父组件数据传递给子组件

父组件中添加数据:value是一个关键的绑定值,所以用v-model,实现双向绑定。

<input-number v-model="value" :max="100" :min="0"></input-number>

在子组件中添加props选项:

 props: {
  max: {
  type: Number,
  default: Infinity
  },
  min: {
  type: Number,
  default: -Infinity
  },
  value: {
  type: Number,
  default: 0
  }
 },

我们知道,Vue组件时单项数据流,所以无法在子组件上更改父组件传递的数据,在这里子组件只改变value值,所以我们给子组件设置一个data数据,默认引用value值,然后在组件内部维护这个data。

data() {
  return{
  // 保存初次父组件传递的数据
  currentValue : this.value,
  }
 }

并且给子组件的input元素绑定value

<input type="text" :value="currentValue" />

这样只解决了初始化时引用父组件value的问题,但是如果父组件修改了value,子组件无法感知,我们想要currentValue一起更新。那么就要使用wacth监听选项监听value。

  • 当父组件value发生变化时,子组件currentValue也跟着变化。
  • 当子组件currentValue变化时,使用$emit触发v-model,使得父组件value也跟着变化
watch: {
  // 监听属性currentValue与value
  currentValue(val) {
  // currentValue变化时,通知父组件的value也变化
  this.$emit('input', val);

  },
  value(val) {
  // 父组件value改变时,子组件currentValue也改变
  this.updataValue(val);
  }
 },
 methods: {
  updataValue(val) {
  if(val > this.max) val = this.max;
  if(val < this.min) val = this.min;
  this.currentValue = val;
  }
  },
  // 第一次初始化时,也对value进行过滤
 mounted: function() {
  this.updataValue(this.value);
 }

上述代码中,生命周期mounted钩子也使用了updateValue()方法,是因为初始化时也要对value进行验证。

父子间的通信解决差不多了,接下来完成按钮的操作:添加handleDown与handleUp方法

template: `
  <div class="input-number">
  <input type="text" :value="currentValue" />
  <button @click="handleDown" :disabled="currentValue <= min">-</button>
  <button @click="handleUp" :disabled="currentValue >= max">+</button>
  </div>
 `,
  methods: {
  updataValue(val) {
  if(val > this.max) val = this.max;
  if(val < this.min) val = this.min;
  this.currentValue = val;
  },
  // 点击减号 减10
  handleDown() {
  if(this.currentValue < this.min) return
  this.currentValue -= this.prop_step;
  },
  // 点击加号 加10
  handleUp() {
  if(this.currentValue < this.min) return
  this.currentValue += this.prop_step;
  },

当用户在输入框想输入具体的值时,怎么办?

为input绑定原生change事件,并且判断输入的是否数字:

<input type="text" :value="currentValue" @change="handleChange" /> 

在methods选项中,添加handleChange方法:

// 输入框输入值
 handleChange(event) {
 var val = event.target.value.trim();
 var max = this.max;
 var min = this.min;
  if(isValueNumber(val)) {
   val = Number(val);
   if(val > max) {
   this.currentValue = max;
   }
   if(val < min) {
   this.currentValue = min;
   }
   this.currentValue = val;
   console.log(this.value);
  }else {
   event.target.value = this.currentValue;
  }

在外层添加判断是否为数字的方法isValueNumber:

function isValueNumber(value) {
 return (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value+ '');
 }

到此一个数字输入框组件基本完成,但是前面提出的后两个要求也需要实现,很简单,在input上绑定一个keydown事件,在data选项中添加数据prop_step

<input type="text" :value="currentValue" @change="handleChange" @keydown="handleChange2" />
data() {
  return{
  // 保存初次父组件传递的数据
  currentValue : this.value,
  prop_step: 10
  }
 }
 // 当聚焦时,按上下键改变
  handleChange2(event) {
  console.log(event.keyCode)
  if(event.keyCode == '38') {
   this.currentValue ++;
  }
  if(event.keyCode == '40') {
   this.currentValue --;
  }
  }

完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <div id="app">
  <input-number v-model="value" :max="100" :min="0"></input-number>
 </div>
</body>
</html>
<script>
 function isValueNumber(value) {
  return (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value+ '');
 }
 Vue.component('input-number',{
  props: {
   max: {
    type: Number,
    default: Infinity
   },
   min: {
    type: Number,
    default: -Infinity
   },
   value: {
    type: Number,
    default: 0
   }
  },
  template: `
   <div class="input-number">
    <input type="text" :value="currentValue" @change="handleChange" @keydown="handleChange2" />
    <button @click="handleDown" :disabled="currentValue <= min">-</button>
    <button @click="handleUp" :disabled="currentValue >= max">+</button>
   </div>
  `,
  data() {
   return{
    // 保存初次父组件传递的数据
    currentValue : this.value,
    prop_step: 10
   }
  },
  watch: {
   // 监听属性currentValue与value
   currentValue(val) {
   // currentValue变化时,通知父组件的value也变化
   this.$emit('input', val);

   },
   value(val) {
   // 父组件value改变时,子组件currentValue也改变
    this.updataValue(val);
   }
  },
  methods: {
   updataValue(val) {
    if(val > this.max) val = this.max;
    if(val < this.min) val = this.min;
    this.currentValue = val;
   },
   // 点击减号 减10
   handleDown() {
    if(this.currentValue < this.min) return
    this.currentValue -= this.prop_step;
   },
   // 点击加号 加10
   handleUp() {
    if(this.currentValue < this.min) return
    this.currentValue += this.prop_step;
   },
   // 输入框输入值
   handleChange(event) {
    var val = event.target.value.trim();
    var max = this.max;
    var min = this.min;
    if(isValueNumber(val)) {
     val = Number(val);
     if(val > max) {
      this.currentValue = max;
     }
     if(val < min) {
      this.currentValue = min;
     }
     this.currentValue = val;
     console.log(this.value);
    }else {
     event.target.value = this.currentValue;
    }
   },
   // 当聚焦时,按上下键改变
   handleChange2(event) {
    console.log(event.keyCode)
    if(event.keyCode == '38') {
     this.currentValue ++;
    }
    if(event.keyCode == '40') {
     this.currentValue --;
    }
   }

  },
  // 第一次初始化时,也对value进行过滤
  mounted: function() {

   this.updataValue(this.value);
  }

 })
 var app = new Vue({
  el:'#app',
  data:{
   value: 5
  }
 })
</script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • vue input输入框模糊查询的示例代码

    Vue 模糊查询功能 原理:原生js的search() 方法,用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串.如果没有找到任何匹配的子串,则返回 -1. input输入框,模糊查询 <template> <div> <input type="text" placeholder="请输入..." v-model="searchVal"> <ul> <li v-for=&quo

  • Vue.js数字输入框组件使用方法详解

    本文实例为大家分享了Vue.js数字输入框组件的具体实现代码,供大家参考,具体内容如下 效果 入口页 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0

  • 基于Vue开发数字输入框组件

    随着 Vue 越来越火热, 相关组件库也非常多啦, 只用轮子怎么够, 还是要造起来!!! 1.概述 Vue组件开发的API:props.events和slots 2.组件代码 github地址:https://github.com/MengFangui/VueInputNumber 效果: (1)index.html <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-

  • vue中使用iview自定义验证关键词输入框问题及解决方法

    一.验证需求 对应配置的关键词输入框,验证要求如下: 1.总字数不能超过7000个: 2.去除配置的关键词特殊符号,得到的关键词组数不能超过300:(如:aaa&(bbb|ccc)|(!ddd|eee)),去掉特殊符号,有5组) 3.单个关键词长度不能超过20:(如:aaaaa&(bbb|ccc)),如果aaaaa长度超过20则提示) 二.解决方法 在关键词输入对应的FormItem中加入一个prop属性,作为验证字段使用:注意该FormItem是包含于Form的: form表单中添加ru

  • vue实现验证码输入框组件

    先来看波完成效果图 需求 输入4位或6位短信验证码,输入完成后收起键盘 实现步骤 第一步 布局排版 <div class="security-code-wrap"> <label for="code"> <ul class="security-code-container"> <li class="field-wrap" v-for="(item, index) in num

  • vue.js实现只能输入数字的输入框

    在菜鸟教程里,看了vue.js的教程,看完后,练练手,就试着实现了只能输入数字的输入框.在之前的博客里,用jquery也实现了这样的功能,这里用vue.js来实现,把实现的过程记录下来 如果只是一个输入框,要实现就非常的简单了,输入框的内容和数据绑定,给数据加一个监听器就可以了,代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue</t

  • Vue实现数字输入框中分割手机号码的示例

    需求 在移动端弹出系统数字键盘,输入手机号码的时候,使用344形式分割. 分析: 首先,如果要在移动端弹出数字键盘,并且还可以有空格,那么就要使用type="phone"的input框 如果要实现输入的时候增加空格,删除的时候减少空格,那么就要使用watch 手机号码为11位,加上两个空格,最多13位,因此要限定长度 代码实现 <body> <div id="app"> <!-- 类型为phone,最大长度为13 --> <

  • vue element-ui实现input输入框金额数字添加千分位

    在util.js中定义方法 包含金额添加过滤千分位,验证金额格式等 const MoneyTest = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/; // 金额添加千分位 const comdify = function (n) { if(!n) return n; let str = n.split('.'); let re = /\d{1,3}(?=(\d{3})+$)/g; let n1 = str[0].replace(re, "$&,");

  • Vue数字输入框组件的使用方法

    最近在通过<Vue.js实战>系统学习Vue,虽然在项目中已多次使用Vue进行开发,但是对于一些非常基础性的知识点还不是很了解,因此这次通过结合数字输入框组件实战来谈谈简单的组件开发. 源代码:数字输入框组件 项目整体结构 ├── src  项目代码 │ ├── common 公共js库 │ │ ├── number.js 判断是否为数字 │ ├── components 组件 │ │ ├── inputCount.vue 数字输入框组件 │ │ ├── inputNumber.vue 数字输

  • Vue数字输入框组件示例代码详解

    数字输入框组件 实现功能:只允许输入数字(包括小数).允许设置初始值.最大值.最小值. 为了方便,这里选用Vue的 cli-service 实现快速原型开发 首先template部分代码 <template> <div class="demo"> <input-number v-model="value" :max="10" :min="0"></input-number> &l

随机推荐