Skip to content

Instantly share code, notes, and snippets.

@ericcgu ericcgu/Vue Currency Input
Last active Apr 24, 2019

Embed
What would you like to do?
Vue Currency Input
</<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>
@ericcgu

This comment has been minimized.

Copy link
Owner Author

commented Feb 6, 2018

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

import currencyinput from './components/CurrencyInput.vue'

Vue.component('currencyinput', currencyinput)

<currencyinput>v-model="price" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"></currencyinput>
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.