We can add a numeric input to our Vue app with the vue-numeric package.
We can install it by running:
npm install vue-numeric --save
Then we can register the plugin by writing the following in main.js
:
import Vue from "vue";
import App from "./App.vue";
import VueNumeric from "vue-numeric";
Vue.use(VueNumeric);
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
to register the VueNumeric
plugin globally.
Then we can write:
<template>
<div id="app">
<vue-numeric currency="$" separator="," v-model="price"></vue-numeric>
<p>{{price}}</p>
</div>
</template>
<script>
export default {
data() {
return {
price: 0
};
}
};
</script>
We have the vue-numeric
component.
It takes the currency
prop to prepend a currency symbol to the input.
separator
adds the separator to our input when it’s displayed.
v-model
binds the inputted value to the price
state.
The currency symbol and the separator are only displayed in the input when we move away from the input.
The value that’s set to price
is still what we typed in, except when we type in something that’s not a whole number.
By default, it doesn’t let us enter decimals.
We can add the :precision
prop to let us enter decimals.
There’s also the minus
prop to let us enter negative numbers.
Also, the placeholder
prop lets us add placeholders.
The output data type can be changed with output-type
.
The empty-value
prop lets us set a default value for the state.
So we can write:
<template>
<div id="app">
<vue-numeric currency="$" separator="," v-bind:precision="2" v-model="price"></vue-numeric>
<p>{{price}}</p>
</div>
</template>
<script>
export default {
data() {
return {
price: 0
};
}
};
</script>
to allow up to 2 decimals to be entered.
The entered value will be converted automatically to the specified format when we move our focus away from the input.
The vue-numeric package lets us add a currency input easily.
It can be adjusted to use a different thousands separator, the numver of decimal digits, and more.