Created
February 27, 2018 08:00
-
-
Save jenky/2d858754c89590cd1db24a0398e05430 to your computer and use it in GitHub Desktop.
Vue input number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div :class="wrapperClass"> | |
<div slot="minus" :class="[buttonClass, 'minus']" @click.prevent="decreaseNumber">-</div> | |
<input type="text" | |
:value="numericValue" | |
@keypress="validateInput" | |
@change="updateValue($event.target.value)" | |
:class="inputClass" | |
:min="min" | |
:max="max" | |
:readonly="readonly" | |
debounce="500"> | |
<div slot="plus" :class="[buttonClass, 'plus']" @click.prevent="increaseNumber">+</div> | |
</div> | |
</template> | |
<script> | |
export default { | |
model: { | |
prop: 'value', | |
event: 'change' | |
}, | |
props: { | |
wrapperClass: { | |
type: String, | |
default: 'tp-total-number' | |
}, | |
readonly: { | |
type: Boolean, | |
default: false | |
}, | |
value: { | |
type: Number, | |
default: 0 | |
}, | |
min: { | |
default: 0, | |
type: Number | |
}, | |
max: { | |
default: 100, | |
type: Number | |
}, | |
step: { | |
default: 1, | |
type: Number | |
}, | |
inputClass: { | |
default: '', | |
type: String | |
}, | |
buttonClass: { | |
default: '', | |
type: String | |
}, | |
integerOnly: { | |
default: false, | |
type: Boolean | |
} | |
}, | |
data () { | |
return { | |
numericValue: this.value | |
} | |
}, | |
watch: { | |
numericValue (val, oldVal) { | |
if (val <= this.min) { | |
this.numericValue = parseInt(this.min) | |
} | |
if (val >= this.max) { | |
this.numericValue = parseInt(this.max) | |
} | |
if (val <= this.max && val >= this.min) { | |
this.$emit('input', val, oldVal ) | |
} | |
} | |
}, | |
methods: { | |
increaseNumber () { | |
this.numericValue += this.step | |
}, | |
decreaseNumber () { | |
this.numericValue -= this.step | |
}, | |
isInteger (evt) { | |
evt = (evt) ? evt : window.event | |
let key = evt.keyCode || evt.which | |
key = String.fromCharCode(key) | |
const regex = /[0-9]/ | |
if (!regex.test(key)) { | |
evt.returnValue = false | |
if (evt.preventDefault) { | |
evt.preventDefault() | |
} | |
} | |
}, | |
isNumber (evt) { | |
evt = (evt) ? evt : window.event | |
var charCode = (evt.which) ? evt.which : evt.keyCode | |
if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) { | |
evt.preventDefault() | |
} | |
else { | |
return true | |
} | |
}, | |
validateInput(evt) { | |
if (this.integerOnly === true) { | |
this.isInteger(evt) | |
} | |
else { | |
this.isNumber(evt) | |
} | |
}, | |
updateValue (value) { | |
this.numericValue = Number(value) | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment