JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/accounting.js/0.4.1/accounting.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdn.rawgit.com/chrisvfritz/5f0a639590d6e648933416f90ba7ae4e/raw/974aa47f8f9c5361c5233bd56be37db8ed765a09/currency-validator.js"></script>
<div id="app">
<currency-input label="Preço" v-model="price"></currency-input>
<currency-input label="Custo de Envio" v-model="shipping"></currency-input>
<currency-input label="Custo de Processamento" v-model="handling"></currency-input>
<currency-input label="Desconto" v-model="discount"></currency-input>
<p>Total: R$ {{ total }}</p>
</div>
JavaScript
Vue.component('currency-input', {
template: '\
<div>\
<label v-if="label">{{ label }}:</label>\
{{ currency }}\
<input\
ref="input"\
v-bind:value="value"\
v-on:input="updateValue($event.target.value)"\
v-on:focus="selectAll"\
v-on:blur="formatValue"\
>\
</div>\
',
props: {
value: {
type: Number,
default: 0
},
label: {
type: String,
default: ''
},
currency: {
type: String,
default: 'R$'
}
},
mounted: function() {
this.formatValue()
},
methods: {
updateValue: function(value) {
var result = currencyValidator.parse(value, this.value)
if (result.warning) {
this.$refs.input.value = result.value
}
this.$emit('input', result.value)
},
formatValue: function() {
this.$refs.input.value = currencyValidator.format(this.value)
},
selectAll: function(event) {
// Workaround for Safari bug
// http://stackoverflow.com/questions/1269722/selecting-text-on-focus-using-jquery-not-working-in-safari-and-chrome
setTimeout(function() {
event.target.select()
}, 0)
}
}
})
new Vue({
el: '#app',
data: {
price: 0,
shipping: 0,
handling: 0,
discount: 0
},
computed: {
total: function() {
return ((
this.price * 100 +
this.shipping * 100 +
this.handling * 100 -
this.discount * 100
) / 100).toFixed(4)
}
}
})