vue输入框组件开发过程详解
时间:2022-11-13 10:14:36|栏目:vue|点击: 次
本文实例为大家分享了vue输入框组件开发过程的具体代码,供大家参考,具体内容如下
input-number.js
function isValueNumber(value) { return(/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9]*$)|(^-?0{1}$)/).test(value + ''); } Vue.component('input-number',{ template: '\ <div class=input-number>\ <input\ type="text"\ :value="currentValue"\ @change="handleChange"\ @focus="keyControl">\ <button \ @click="handleDown" \ :disabled="currentValue<=min">-</button>\ <button \ @click="handleUp" \ :disabled="currentValue>=max">+</button>\ </div>', data: function (){ return { currentValue: this.value, currentStep: this.$parent.step } }, watch: { currentValue: function (val){ this.$emit('input',val); this.$emit('on-change',val); }, value: function(val){ this.updateValue(val); } }, methods: { handleDown: function(){ if(this.currentValue<=this.min) return; this.currentValue-=this.currentStep; }, handleUp: function(){ if(this.currentValue>=this.max) return; this.currentValue+=this.currentStep; }, updateValue: function(val){ if(val>this.max) val=this.max; if(val<this.min) val=this.min; this.currentValue=val; }, handleChange: function(event){ var val = event.target.value.trim(); var max = this.max; var min = this.min; if(isValueNumber(val)) { val = Number(val); this.currentValue = val; if(val > max) { this.current = max; } if(val < min) { this.current = min; } } else { //如果输入的不是数字,将输入的内容重置为之前的currentValue event.target.value = this.currentValue; } }, keyControl: function(){ var _this=this; $(window).keydown(function(e){ if($('input')){ if(e.keyCode==38){ _this.handleUp(); } else if(e.keyCode==40){ _this.handleDown(); } } }); } }, mounted: function(){ this.updateValue(this.value); }, props:{ max:{ type: Number, default: Infinity }, min: { type: Number, default: -Infinity }, value: { type:Number, default: 0 }, step: { type:Number, default: 1 } } })
index.js
var app=new Vue({ el: "#app", data: { value: 5, step: 10 } })
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script> <script src="js/vue.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div id="app"> <input-number v-model="value" :max="100" :min="0"></input-number> </div> <script src="js/input-number.js" type="text/javascript" charset="utf-8"></script> <script src="js/index.js" type="text/javascript" charset="utf-8"></script> </body> </html>