Skip to content

Instantly share code, notes, and snippets.

@postpostscript
Last active June 6, 2019 14:52
Show Gist options
  • Save postpostscript/3303400b5996e90451bfbb28628dc657 to your computer and use it in GitHub Desktop.
Save postpostscript/3303400b5996e90451bfbb28628dc657 to your computer and use it in GitHub Desktop.
Vue NumberInput component allowing for shift + arrow key to jump up and down by a specified amount
<template>
<input type="number" @keydown.native="onKeydown" :value="value" @input="onInput" :min="min" :max="max" :step="step" v-bind="$attrs" />
</template>
<script>
export default {
name: 'NumberInput',
props: {
value: {
type: Number,
},
jump: {
type: Number,
default: 1,
},
step: {
type: [Number, String],
default: 'any',
},
min: {
type: Number,
default: 0,
},
max: {
type: Number,
required: false,
},
keyCodes: {
type: Object,
default() {
return {
'ArrowUp': 1,
'ArrowDown': -1,
}
},
},
},
methods: {
onKeydown(event) {
if (!(Object.keys(this.keyCodes).includes(event.key) && event.shiftKey)) {
return
}
event.preventDefault()
const direction = this.keyCodes[event.key]
const currentValue = (typeof this.value === 'number' && !isNaN(this.value) ? this.value : this.min)
let value = currentValue + direction * this.jump
value = Math.max(this.min, value)
if (this.max > this.min) {
value = Math.min(this.max, value)
}
this.$emit('input', value)
return false
},
onInput(value) {
if (value && parseFloat(value) != value) {
return
}
this.$emit('input', parseFloat(value))
},
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment