Skip to content

Instantly share code, notes, and snippets.

@ericcgu
Last active April 24, 2019 15:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericcgu/b4b16a6f7ce73c5329c4c395f02896c5 to your computer and use it in GitHub Desktop.
Save ericcgu/b4b16a6f7ce73c5329c4c395f02896c5 to your computer and use it in GitHub Desktop.
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
Copy link
Author

ericcgu 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