1. 程式人生 > 程式設計 >Vue數字輸入框元件使用方法詳解

Vue數字輸入框元件使用方法詳解

前面的話

關於基礎元件介紹,已經更新完了。這篇文章將用元件基礎知識開發一個數字輸入框元件。將涉及到指令、事件、元件間通訊。

Vue數字輸入框元件使用方法詳解

基礎需求

  • 只能輸入數字
  • 設定初始值,最大值,最小值
  • 在輸入框聚焦時,增加對鍵盤上下鍵的支援
  • 增加一個控制步伐prop-step,例如,設定為10 ,點選加號按鈕,一次增加10

專案搭建

在瞭解需求後,進行專案的初始化:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width,initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <div id="app">
 <input-number></input-number>
 </div>
</body>
</html>
<script>
 Vue.component('input-number',{
 template: `
  <div class="input-number">
  <input type="text" />
  <button>-</button>
  <button>+</button>
  </div>
 `}
 var app = new Vue({
 el:'#app'
 })
</script>

初始化結構搭好後,由於要設定初始值,最大值、最小值,我們在父元件中的 < input-number>< /input-number>上設定這些值,並且通過Props將父元件資料傳遞給子元件

父元件中新增資料:value是一個關鍵的繫結值,所以用v-model,實現雙向繫結。

<input-number v-model="value" :max="100" :min="0"></input-number>

在子元件中新增props選項:

 props: {
  max: {
  type: Number,default: Infinity
  },min: {
  type: Number,default: -Infinity
  },value: {
  type: Number,default: 0
  }
 },

我們知道,Vue元件時單項資料流,所以無法在子元件上更改父元件傳遞的資料,在這裡子元件只改變value值,所以我們給子元件設定一個data資料,預設引用value值,然後在元件內部維護這個data。

data() {
  return{
  // 儲存初次父元件傳遞的資料
  currentValue : this.value,}
 }

並且給子元件的input元素繫結value

<input type="text" :value="currentValue" />

這樣只解決了初始化時引用父元件value的問題,但是如果父元件修改了value,子元件無法感知,我們想要currentValue一起更新。那麼就要使用wacth監聽選項監聽value。

  • 當父元件value發生變化時,子元件currentValue也跟著變化。
  • 當子元件currentValue變化時,使用$emit觸發v-model,使得父元件value也跟著變化
watch: {
  // 監聽屬性currentValue與value
  currentValue(val) {
  // currentValue變化時,通知父元件的value也變化
  this.$emit('input',val);
  

  },value(val) {
  // 父元件value改變時,子元件currentValue也改變
  this.updataValue(val);
  }
 },
 methods: {
  updataValue(val) {
  if(val > this.max) val = this.max;
  if(val < this.min) val = this.min;
  this.currentValue = val;
  }
  },// 第一次初始化時,也對value進行過濾
 mounted: function() {
  this.updataValue(this.value);
 }

上述程式碼中,生命週期mounted鉤子也使用了updateValue()方法,是因為初始化時也要對value進行驗證。

父子間的通訊解決差不多了,接下來完成按鈕的操作:新增handleDown與handleUp方法

template: `
  <div class="input-number">
  <input type="text" :value="currentValue" />
  <button @click="handleDown" :disabled="currentValue <= min">-</button>
  <button @click="handleUp" :disabled="currentValue >= max">+</button>
  </div>
 `,methods: {
  updataValue(val) {
  if(val > this.max) val = this.max;
  if(val < this.min) val = this.min;
  this.currentValue = val;
  },// 點選減號 減10
  handleDown() {
  if(this.currentValue < this.min) return 
  this.currentValue -= this.prop_step;
  },// 點選加號 加10 
  handleUp() {
  if(this.currentValue < this.min) return
  this.currentValue += this.prop_step;
  },

當用戶在輸入框想輸入具體的值時,怎麼辦?

為input繫結原生change事件,並且判斷輸入的是否數字:

<input type="text" :value="currentValue" @change="handleChange" /> 

在methods選項中,新增handleChange方法:

// 輸入框輸入值
 handleChange(event) {
 var val = event.target.value.trim();
 var max = this.max;
 var min = this.min;
  if(isValueNumber(val)) {
   val = Number(val);
   if(val > max) {
   this.currentValue = max;
   }
   if(val < min) {
   this.currentValue = min;
   }
   this.currentValue = val;
   console.log(this.value);
  }else {
   event.target.value = this.currentValue;
  }

在外層新增判斷是否為數字的方法isValueNumber:

function isValueNumber(value) {
 return (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value+ '');
 }

到此一個數字輸入框元件基本完成,但是前面提出的後兩個要求也需要實現,很簡單,在input上繫結一個keydown事件,在data選項中新增資料prop_step

<input type="text" :value="currentValue" @change="handleChange" @keydown="handleChange2" />
data() {
  return{
  // 儲存初次父元件傳遞的資料
  currentValue : this.value,prop_step: 10
  }
 }
 // 當聚焦時,按上下鍵改變
  handleChange2(event) {
  console.log(event.keyCode)
  if(event.keyCode == '38') {
   this.currentValue ++;
  }
  if(event.keyCode == '40') {
   this.currentValue --;
  }
  }

完整程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width,initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
 <div id="app">
  <input-number v-model="value" :max="100" :min="0"></input-number>
 </div>
</body>
</html>
<script>
 function isValueNumber(value) {
  return (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(value+ '');
 }
 Vue.component('input-number',{
  props: {
   max: {
    type: Number,default: Infinity
   },min: {
    type: Number,default: -Infinity
   },value: {
    type: Number,default: 0
   }
  },template: `
   <div class="input-number">
    <input type="text" :value="currentValue" @change="handleChange" @keydown="handleChange2" />
    <button @click="handleDown" :disabled="currentValue <= min">-</button>
    <button @click="handleUp" :disabled="currentValue >= max">+</button>
   </div>
  `,data() {
   return{
    // 儲存初次父元件傳遞的資料
    currentValue : this.value,prop_step: 10
   }
  },watch: {
   // 監聽屬性currentValue與value
   currentValue(val) {
   // currentValue變化時,通知父元件的value也變化
   this.$emit('input',val);
   

   },value(val) {
   // 父元件value改變時,子元件currentValue也改變
    this.updataValue(val);
   }
  },methods: {
   updataValue(val) {
    if(val > this.max) val = this.max;
    if(val < this.min) val = this.min;
    this.currentValue = val;
   },// 點選減號 減10
   handleDown() {
    if(this.currentValue < this.min) return 
    this.currentValue -= this.prop_step;
   },// 點選加號 加10 
   handleUp() {
    if(this.currentValue < this.min) return
    this.currentValue += this.prop_step;
   },// 輸入框輸入值
   handleChange(event) {
    var val = event.target.value.trim();
    var max = this.max;
    var min = this.min;
    if(isValueNumber(val)) {
     val = Number(val);
     if(val > max) {
      this.currentValue = max;
     }
     if(val < min) {
      this.currentValue = min;
     }
     this.currentValue = val;
     console.log(this.value);
    }else {
     event.target.value = this.currentValue;
    }
   },// 當聚焦時,按上下鍵改變
   handleChange2(event) {
    console.log(event.keyCode)
    if(event.keyCode == '38') {
     this.currentValue ++;
    }
    if(event.keyCode == '40') {
     this.currentValue --;
    }
   }

  },// 第一次初始化時,也對value進行過濾
  mounted: function() {
   
   this.updataValue(this.value);
  }


 })
 var app = new Vue({
  el:'#app',data:{
   value: 5
  }
 })
</script>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。