我們對普通輸入框進行擴展,實現一個可快捷輸入數字組件。
首先制定規則:
接著,規劃好 API。一個 Vue.js 組件最重要的 3 個部分就是 props、events 以及 slot,我們需要定義這三個部分的命名以及業務規則。這個組件比較簡單,所以我們只用到 props 與 events。
1 基礎版
html:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>數字輸入組件</title></head><body><div id="app"> <number-input v-model="value" :min="0" :max="6"></number-input></div><script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script><script src="number.js"></script><script> var app = new Vue({ el: '#app', data: { value: 3 } });</script></body></html>
這里,我們使用了 v-model,雙向綁定了 value。
number.js:
/** * 是否為數字 * @param val * @returns {boolean} */function isNum(val) { return (/^[0-9]*$/).test(val);}/** * 數字輸入組件 */Vue.component('number-input', { template: '/ <div class="number-input">/ <input / type="text"/ :value="currentVal"/ @change="change">/ <button/ @click="down"/ :disabled="currentVal<=min">-</button>/ <button/ @click="up"/ :disabled="currentVal >=max">+</button>/ </div>', props: {//校驗 //最大值 max: { type: Number, default: Infinity }, //最小值 min: { type: Number, default: -Infinity }, //初始值 value: { type: Number, default: 0 } }, data: function () { return { currentVal: this.value } }, watch: { currentVal: function (val) { console.log("currentVal:" + this.currentVal); this.$emit('input',val); }, value: function (val) {//更新 currentVal this.update(val); } }, methods: { /** * 更新 * @param val */ update: function (val) { //讓輸入的值在限定范圍內 if (val > this.max) { val = this.max; } if (val < this.min) { val = this.min } this.currentVal = val; }, /** * 減少 */ down: function () { if (this.currentVal <= this.min) { return; } this.currentVal -= 1; }, /** * 增長 */ up: function () { if (this.currentVal >= this.max) { return; } this.currentVal += 1; }, /** * 如果輸入的值, * @param event */ change: function (event) { var val = event.target.value.trim();//獲取輸入值 if (isNum(val)) {//賦值 currentVal val = Number(val); this.currentVal = val; //超出限定范圍時,規整 var max = this.max; var min = this.min; if (val > max) { this.currentVal = max; } else if (val < min) { this.currentVal = min; } } else {//還原為 currentVal event.target.value = this.currentVal; } } }, mounted: function () { //對初始值進行范圍限定 this.update(this.value); }});
這里,我們專門定義了一個 number.js,用于定義數字輸入組件。
在 number.js 中,我們做了如下工作:
效果:
2 按鍵支持
當輸入框獲得焦點時,按下“向上鍵”時,增長;按下“向上鍵”時,減少。
這可以利用按鍵修飾符來實現,我們修改示例中的組件模板:
... <input type="text" :value="currentVal" @change="change" @keyup.up="up" @keyup.down="down">...
Vue.js 定義按鍵別名有這些:
效果:
3 控制步伐
新增一個步伐屬性,增長或者減少以步伐值為變化量。之前的示例,步伐為 1。
首先在 props 中,定義一個步伐屬性:
//步伐step: { type: Number, default: 1}
然后在增長與減少函數中,使用步伐屬性做為變化量:
/** * 減少 */down: function () { if (this.currentVal <= this.min) { return; } this.currentVal -= this.step;},/** * 增長 */up: function () { if (this.currentVal >= this.max) { return; } this.currentVal += this.step;},
最后為組件重新配置參數:
<number-input v-model="value" :min="0" :max="50" :step="5"></number-input>
效果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答