使用Vue中的组件封装一个小按钮(详细)
html部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> <script type="text/javascript" src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> </head> <body> <div id="app"> <input-number :max="20" :min="0" v-model="value"></input-number> </div> </body> </html> <script type="text/javascript" src="input-number.js"></script> <script type="text/javascript" src="index.js"></script> |
组件部分(input-number.js)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | function isValueNumber(value) { console.log(1); return value; } // 注意在编译的过程中,模板中不能有空行,有空行就会报错 Vue.component('input-number', { created: function () { console.log("开始的时候触发"); }, template: ` <div class="input-number"> <input type="text" :value="currentValue" @change="handleChange" @keyup.down="handleDown" @keyup.up="handleUp" > <button @click="handleDown" :disabled="currentValue <= min">-</button> <button @click="handleUp" :disabled="currentValue >= max">+</button> </div> `, props: { max: { type: Number, default: Infinity }, min: { type: Number, default: -Infinity }, value: { type: Number, default: 0 } }, data: function () { return { currentValue: this.value } }, watch: { /* 1、父组件可以使用 props 把数据传给子组件。 2、子组件可以使用 $emit 触发父组件的自定义事件。 vm.$emit( event, arg ) //触发当前实例上的事件 vm.$on( event, fn );//监听event事件后运行 fn; */ currentValue: function (val) { this.$emit('input', val); this.$emit('on-change', val); } }, methods: { handleDown: function () { if (this.currentValue <= this.min) return; this.currentValue -= 1; }, handleUp: function () { if (this.currentValue >= this.max) return; this.currentValue += 1; }, 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.currentValue = max; } else if (val < min) { this.currentValue = min; } } else { event.target.value = this.currentValue; } } }, //mounted 第一次加载调用完毕之后触发 mounted: function () { console.log(this.value); this.updateValue(this.value); } }) |
调用部分(index.js)
1 2 3 4 5 6 | var app = new Vue({ el:"#app", data:{ value:0 } }) |
7