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>
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。