Skip to content

Instantly share code, notes, and snippets.

@porfirion
Created October 13, 2020 16:39
Show Gist options
  • Save porfirion/a9417aeba2cce3446a538b741467be93 to your computer and use it in GitHub Desktop.
Save porfirion/a9417aeba2cce3446a538b741467be93 to your computer and use it in GitHub Desktop.
Vue.js 3 minimalistic number input
export default {
props: {
modelValue: [Number, String],
min: {
type: [Number, String],
default: null,
},
max: {
type: [Number, String],
default: null,
}
},
methods: {
inc() {
let newValue = Number(this.modelValue) + 1;
if (this.max != null) {
if (newValue > Number(this.max)) {
newValue = Number(this.max)
}
}
this.updateValue(newValue);
},
dec() {
let newValue = Number(this.modelValue) - 1;
if (this.min != null) {
if (newValue < Number(this.min)) {
newValue = Number(this.min);
}
}
this.updateValue(newValue);
},
updateValue(newValue) {
this.$emit('update:modelValue', newValue)
},
},
template: `<div class="number-input">
<button class="number-input__button" @click="dec">-</button>
<input class="number-input__input"
type="number"
:value="modelValue"
:min="min"
:max="max"
@input="$emit('update:modelValue', $event.target.value)"/>
<button class="number-input__button" @click="inc">+</button>
</div>`,
}
@porfirion
Copy link
Author

porfirion commented Oct 13, 2020

Minimalistic number input with inc/dec buttons for Vue.js 3

Supports min and max value both for buttons and native input up/down controls.

Usage:

import NumberInput from "./NumberInput.js";
let myVariableName = 10

<NumberInput v-model="myVariableName" min="5" max="15"/>

Associated styles:

.number-input {
    display: flex;
    width: auto;
    min-width: auto;
    max-width: 100%;
}

.number-input__input {
    min-width: 0;
    flex: 1 0 10px;
}
.number-input__button {
    flex: 0 0 30px;
    padding: 0;
}
.number-input__button + .number-input__input {
    margin-left: -2px;
}
.number-input__input + .number-input__button {
    margin-left: -2px;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment