Last active
October 25, 2019 14:51
-
-
Save earthboundkid/0fe5efb56bab070de2222e5c0c347072 to your computer and use it in GitHub Desktop.
This file contains 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 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