Skip to content

Instantly share code, notes, and snippets.

@ravipatel2293
Last active July 21, 2020 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravipatel2293/308fd0b677e8b05a92a3015a00ddb8b4 to your computer and use it in GitHub Desktop.
Save ravipatel2293/308fd0b677e8b05a92a3015a00ddb8b4 to your computer and use it in GitHub Desktop.
<template>
<input type="text" :value="maskedValue" :ref="'inputRef'" @input="handleInput($event)">
</template>
<script>
export default {
name: "Input",
model: {
prop: "hiddenValue",
event: "blur"
},
props: {
hiddenValue: {
type: [String, Number]
}
},
computed: {
maskedValue() {
const vm = this
if (!vm.hiddenValue) {
return 0
}
// Convert number value to string
let maskedVal = String(vm.hiddenValue)
// Split the amount in array if value in decimal
// First part contains value befire decimal point
// Second part contains value after decimal point
let parts = maskedVal.split(".")
// Apply regex for mask the fisrt part
// It will transform the first part into the comma seperated value
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
return parts.join(".")
}
},
methods: {
handleInput(event) {
const vm = this
let unMaskedVal = null
// Split the amount in array if value in decimal
let parts = event.target.value.split(".")
// Now unmask the value by applying reverse logic
parts[0] = parts[0].split(',').join("")
unMaskedVal = parseFloat(parts.join("."))
// Emit the blur event so it automatically sets the hiddenValue
vm.$emit("blur", unMaskedVal)
}
}
};
</script>
<style scoped>
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment