vue --- vue.js实战基础篇课后练习
生活随笔
收集整理的這篇文章主要介紹了
vue --- vue.js实战基础篇课后练习
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
練習(xí)1:在輸入框聚焦時(shí),增加對(duì)鍵盤上下鍵按鍵的支持,相當(dāng)于加1和減1
練習(xí)2:增加一個(gè)控制步伐的prop-step,比如設(shè)置為10,點(diǎn)擊加號(hào)按鈕,一次增加10
思路:
// 考慮到子模板的復(fù)用性,即在父模板中復(fù)用如下: <input-number v-model="value" :max="10" :min="0" :step="3"></input-number> // v-model將input中的值和父模板data下面value的值綁定到一起 // 可以通過:max,:min限制輸入框的最大最小值 // 通過:step來設(shè)置子模版點(diǎn)擊加號(hào)時(shí)的步伐(即,一次加多少)幾個(gè)補(bǔ)充:
@focus: 用于綁定input的聚焦事件
@blur: 用于綁定input的失去焦點(diǎn)事件
@keyup.down: 綁定鍵盤的向下鍵
@keyup.up: 綁定鍵盤的向上鍵
總體代碼如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body><div id="app"><input-number v-model="value" :max="10" :min="0" :step="3"></input-number></div><script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script> <script>Vue.component('input-number',{template:'\<div class="input-number">\<input type="text" :value="currentValue" @change="handleChange" @focus="handleFocus" @blur="handleBlur" @keyup.down="handleArrowDown" @keyup.up="handleArrowUp">\<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},step:{type:Number,default:1}},data:function (){return {currentValue: this.value,isFocus:false}},methods:{handleUp:function() {this.currentValue += this.step;},handleDown:function() {this.currentValue -= this.step;},isValueNumber:function(value) {return (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value + '');},handleChange:function(event){let val = event.target.value.trim();let max = this.max;let min = this.min;if(this.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;}},updateValue:function(val){if(val > this.max) val = this.max;if(val < this.min) val = this.min;this.currentValue = val;},handleFocus:function(){this.isFocus = true},handleBlur:function(){this.isFocus = false},handleArrowDown:function(){if(this.isFocus){this.handleDown();}},handleArrowUp:function(){if(this.isFocus){this.handleUp();}}},watch:{currentValue: function(val) {this.$emit('input',val);},value: function(val){this.updateValue(val);}}})const app = new Vue({el:'#app',data:{value:5}}) </script></body> </html>參考《Vue.js實(shí)戰(zhàn)》P98~P106
總結(jié)
以上是生活随笔為你收集整理的vue --- vue.js实战基础篇课后练习的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: echarts --- 多折线图按段显
- 下一篇: 如何获取qq群成员的资料信息(爬虫)