index.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>数字输入组件</title> 6 </head> 7 <body> 8 <div id="app"> 9 <input-number v-model="value" :max="10" :min="0"><input-number> 10 </div> 11 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> 12 <script src="input-number.js"></script> 13 <script src="index.js"></script> 14 </body> 15 </html>
index.js
1 var app = new Vue({ 2 el: '#app', 3 data: { 4 value: 5 5 } 6 })
input-number.js
1 function isValueNumber(value) { 2 return (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value + ''); 3 } 4 5 Vue.component('input-number', { 6 template:'\ 7 <div class="input-number">\ 8 <input\ 9 type="text"\ 10 :value="currentValue"\ 11 @change="handleChange">\ 12 <button\ 13 @click="handleDown"\ 14 :disabled="currentValue <= min">-</button>\ 15 <button\ 16 @click="handleUp"\ 17 :disabled="currentValue >= max">+</button>\ 18 </div>', 19 props: { 20 max: { 21 type: Number, 22 default: Infinity 23 }, 24 min: { 25 type: Number, 26 default: -Infinity 27 }, 28 value: { 29 type: Number, 30 default: 0 31 } 32 }, 33 data: function() { 34 return { 35 currentValue: this.value 36 } 37 }, 38 watch: { 39 currentValue: function(val) { 40 this.$emit('input', val); 41 this.$emit('on-change', val); 42 }, 43 value: function(val) { 44 this.updateValue(val); 45 } 46 }, 47 methods: { 48 updateValue: function(val) { 49 if(val > this.max) val = this.max; 50 if(val < this.min) val = this.min; 51 this.currentValue = val; 52 }, 53 handleDown: function() { 54 if(this.currentValue <= this.min) return; 55 this.currentValue -= 1; 56 }, 57 handleUp: function() { 58 if(this.currentValue >= this.max) return; 59 this.currentValue += 1; 60 }, 61 handleChange: function(event) { 62 var val = event.target.value.trim(); 63 var max = this.max; 64 var min = this.min; 65 66 if(isValueNumber(val)) { 67 val = Number(val); 68 this.currentValue = val; 69 70 if(val > max) { 71 this.currentValue = max; 72 }else { 73 console.log(event); 74 event.target.value = this.currentValue; 75 } 76 } 77 } 78 79 }, 80 mounted: function() { 81 this.updateValue(this.value); 82 } 83 84 })