Skip to content

Instantly share code, notes, and snippets.

@robmcalister
Forked from anonymous/fiddle.css
Created March 16, 2018 05:25
Show Gist options
  • Save robmcalister/cd0a2d34824d7b2f1c29d5e6ed1973d6 to your computer and use it in GitHub Desktop.
Save robmcalister/cd0a2d34824d7b2f1c29d5e6ed1973d6 to your computer and use it in GitHub Desktop.
Formatted currency input component using Vue.js (source: https://jsfiddle.net/mani04/bgzhw68m/)
body {
margin: 20px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
input {
border: 1px solid #888;
font-size: 1.2rem;
padding: 0.5rem;
}
<body>
<div id="app">
Price:
<my-currency-input v-model="price"></my-currency-input>
<p>
Price (in parent component): {{price}}
</p>
</div>
</body>
Vue.component('my-currency-input', {
props: ["value"],
template: `
<div>
<input type="text" v-model="displayValue" @blur="isInputActive = false" @focus="isInputActive = true"/>
</div>`,
data: function() {
return {
isInputActive: false
}
},
computed: {
displayValue: {
get: function() {
if (this.isInputActive) {
// Cursor is inside the input field. unformat display value for user
return this.value.toString()
} else {
// User is not modifying now. Format display value for user interface
return "$ " + this.value.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")
}
},
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)
}
}
}
});
new Vue({
el: '#app',
data: function() {
return {
price: 1234
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment