Many AJAX frameworks have built-in support for formatting. Vue used to, but support was removed in Vue 3 --- the developers decided that there are many good formatting libraries available (including some built directly into JavaScript) and Vue has good support for integrating these frameworks. Supporting the formatting code directly was adding uneccessary complexity to the framework, so they removed it.
We can easily add our own formatting functions to our application via Vue mixins.
Create a new JavaScript file named number-formatter
.
Add the following code to the file:
export const NumberFormatter = { methods: { formatCurrency(value) { return Intl.NumberFormat('en-NZ',{style: "currency", currency: 'NZD'}).format(value); }, formatNumber(value, decimalPlaces) { // cast to number in case value is a string let number = Number(value); return number.toFixed(decimalPlaces); } } }
This is using the built-in formatting functions that JavaScript has.
To add this module as a mixin you add another block to your JavaScript files (products-list.js
, and cart.js
):
mixins:[NumberFormatter]
This goes at the same level as the other blocks (data
, methods
, mounted
, etc.).
You also need to import the module in each of the JavaScript files that is making use of it:
import { NumberFormatter } from './number-formatter.js';
Add this at the bottom of the file, just above the app.mount
call.
You can use the functions in your HTML templates as follows:
<td>{{ formatCurrency(product.listPrice) }}</td> <td>{{ formatNumber(product.quantityInStock, 2) }}</td>