labs / tiddlers / content / labs / lab09 / _Labs_09_Formatting

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.

  1. Create a new JavaScript file named number-formatter.

  2. 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.

  3. To add this module as a mixin you add another block to your JavaScript files (products-list.js, and cart.js):


    This goes at the same level as the other blocks (data, methods, mounted, etc.).

  4. 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.

  5. You can use the functions in your HTML templates as follows:

     <td>{{ formatCurrency(product.listPrice) }}</td>
     <td>{{ formatNumber(product.quantityInStock, 2) }}</td>