bekwam courses

Vue.js Filters to Format Output

May 5, 2019

Filters are the preferred technique to format output in Vue.js. While you can create a computed property to mirror a raw field value, filters eliminate the need for these trivial properties. Moreover, reuse is heightened by parameterizing the filter.

Sample App

This screenshot shows the program outputting four data items: a raw US phone number, a formatted US phone number, a raw UK phone number, and a formatted UK phone number. These items are rendered off of two data fields: usPhone and ukPhone. A filter is applied to each of the numbers that renders the output differently.

Browser Showing App
Raw and Formatted Data Elements

The app uses a single Vue App instance. A formatPhone() function is defined in the filters option. In the template, raw data elements are output using the mustache {{}} syntax. The formatted elements also use the mustache syntax, but extend the raw syntax with a pipe to the filter function. There is also a parameter that is added for each pairing. A "US" parameter triggers the US formatting and a "UK" parameter triggers the UK formatting.

This is the code listing for the app. There is a trivial index.html that loads a main.js file.


new Vue({
  el: "#app",
  template: `
      <div>
        <h2>US Phone</h2>
        <p>Raw: {{ usPhone }}</p>
        <p>Formatted {{ usPhone | formatPhone('US') }}</p>
        <h2>UK Phone</h2>
        <p>Raw: {{ ukPhone }}</p>
        <p>Formatted {{ ukPhone | formatPhone('UK')}}</p>
      </div>
    `,
  data: {
    usPhone: "2402888381",
    ukPhone: "447911123456" 
  },
  filters: {
    formatPhone(phn, country) {
      switch(country) {
        case "US":
          return "(" + phn.substring(0,3) + ") " + phn.substring(3,6) + "-" + phn.substring(6);
        case "UK":
          return "+" + phn.substring(0,2) + " " + phn.substring(2,6) + " " + phn.substring(6);
        default:
          return country;
      }
    }
  }
});

The bar syntax as in "usPhone | formatPhone" associates a filter with a data field. This can be extended, say to provide additional formatting with more filters. Say you have a money value in mils (1234546). You might convert to a mils value (1234.546) in one filter and then add a currency symbol in another (result: $1234.546). The syntax would look like {{ totalValue | toDecimal | toCurrency }}.

This article presented a Vue.js app that formatted two phone numbers based on their locale. If other code modules need this same formatting, you can extract the definition for formatPhone() currently in the filters assignment into a separate code module and simply use filters: { formatPhone }.


Headshot of Carl Walker

By Carl Walker

President and Principal Consultant of Bekwam, Inc