1. 程式人生 > 程式設計 >Vue數字輸入框元件示例程式碼詳解

Vue數字輸入框元件示例程式碼詳解

數字輸入框元件

實現功能:只允許輸入數字(包括小數)、允許設定初始值、最大值、最小值。

為了方便,這裡選用Vue的 cli-service

實現快速原型開發

首先template部分程式碼

<template>
 <div class="demo">
  <input-number v-model="value" :max="10" :min="0"></input-number>
 </div>
</template>

這部分沒有什麼特別說明的,分別傳入 value、max、min 作為子元件的原始值最大值和最小值。在子元件中用 props 接收,獨立元件,對每個傳入的prop進行型別驗證

主要JS部分程式碼

<script>
import Vue from 'vue'
Vue.component('input-number',{
 props: {
  value: {
   type: Number,default: 0
  },max: {
   type: Number,default: Infinity
  },min: {
   type: Number,default: -Infinity
  }
 },data() {
  return {
   currentValue: this.value
  }
 },render(cr) {
  let _this = this
  ...
 }
})
export default {
 data() {
  return {
   value: 5
  }
 }
}
</script>

在這裡不能使用字串的方式定義元件模板,所以使用 render() 函式的方式

render(cr) {
 let _this = this
 return cr('div',{'class': 'input-number'},[
  cr('button',{'class': {'down-btn':true,'dis':this.currentValue<=this.min},on: {click: _this.handleDown},},['-']),cr('input',{'class': 'change-input',domProps: {value: _this.currentValue},on: {change: _this.handleChange}}),cr('button','dis':this.currentValue>=this.max},on: {click: _this.handleUp},['+']),])
}

定義 watch 和 methods

watch: {
 value(val) {
  this.updateValue(val)
 },currentValue(val) {
  this.$emit('input',val)
  this.$emit('on-change',val)
 }
},methods: {
 updateValue(val) {
  if(val > this.max) val = this.max
  if(val < this.min) val = this.min
  this.currentValue = val
 },handleDown() {
  if(this.currentValue<=this.min) return
  this.currentValue-=1
 },handleUp() {
  if(this.currentValue>=this.max) return
  this.currentValue+=1
 },handleChange(ev) {
  let val = ev.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 {
   ev.target.value = this.currentValue
  }
 },isValueNumber(val) {
  return (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/).test(val+'')
 }
}

最後是Less部分程式碼

<style lang="less">
* {
 box-sizing: border-box;
}
.demo {
 width: 200px;
 margin: 0 auto;
}
.input-number {
 width: 100%;
 display: flex;
 height: 40px;
 align-items: center;
 justify-content: space-between;
 .down-btn,.up-btn {
  font-size: 18px;
  width: 40px;
  height: 40px;
  background-color: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 4px 0 0 4px;
  cursor: pointer;
  outline: none;
  &.up-btn {
   border-radius: 0 4px 4px 0;
  }
  &.dis {
   cursor: not-allowed;
  }
 }
 .change-input {
  flex: 1;
  max-width: 100px;
  outline: none;
  border: none;
  text-align: center;
  height: 40px;
 }
}
</style>

總結

以上所述是小編給大家介紹的Vue數字輸入框元件示例程式碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!