Last active
April 24, 2019 15:30
-
-
Save ericcgu/b4b16a6f7ce73c5329c4c395f02896c5 to your computer and use it in GitHub Desktop.
Vue Currency Input
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> | |
<el-input type="text" v-model="displayValue" @blur="isInputActive = false" @focus="isInputActive = true" /> | |
</div> | |
</template> | |
<script> | |
export default { | |
props: ["value"], | |
data: function () { | |
return { | |
isInputActive: false | |
} | |
}, | |
computed: { | |
displayValue: { | |
get: function () { | |
if (this.value == null) return '' | |
if (this.isInputActive) { | |
// Cursor is inside the input field. unformat display value for user | |
return this.value.toString() | |
} else { | |
var formatter = new Intl.NumberFormat('en-IN', { | |
minimumFractionDigits: 0, | |
// the default value for minimumFractionDigits depends on the currency | |
// and is usually already 2 | |
}); | |
return formatter.format(this.value) | |
} | |
}, | |
set: function (modifiedValue) { | |
// Recalculate value after ignoring "$" and "," in user input | |
let newValue = parseFloat(modifiedValue.replace(/[^\d\.]/g, "")) | |
// Ensure that it is not NaN | |
if (isNaN(newValue)) { | |
newValue = 0 | |
} | |
// Note: we cannot set this.value as it is a "prop". It needs to be passed to parent component | |
// $emit the event so that parent component gets it | |
this.$emit('input', newValue) | |
} | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you add the below it will prevent input of non-numeric and symbols and supports lazy formatting.
Lazy formatting allows for copy and paste of actual float.
In main.js or entry js file of your app