Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<template>
<div id="app">
Value is "{{ value }}". <br />
<input v-model="value" @input="handleChange($event)" />
</div>
</template>
<script>
function trimAndSpace(val) {
return val
.replace(/\D/gi, "")
.replace(/(.{4})/g, "$1 ")
.trim();
}
export default {
name: "App",
data() {
return {
value: "",
lastValue: ""
};
},
methods: {
handleChange(event) {
const lastValueLength = this.lastValue.length;
const curValueLength = this.value.length;
this.lastValue = this.value;
// handle backspace event
if (curValueLength < lastValueLength) {
return;
}
const el = event.target;
const startPos = el.selectionStart;
this.value = trimAndSpace(this.value);
// handle value-edit event
if (startPos < curValueLength) {
this.$nextTick(() => {
el.focus();
el.setSelectionRange(startPos, startPos);
});
}
}
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.