Format Data Using Vue Filters

Vue filters provide an excellent way to format data on the UI. Define Vue filters using a filter: block in single file components, or use global filters.

Consider the following use cases -

  1. Purchase date is stored in yyyy-mm-dd in DB, but you have to display dd-mm-yyyy format
  2. Cost data needs to be displayed in currency of user’s locale
  3. Apply separators in bill number for better readability

These and many more are easily accomplished in Vue filters. Let us consider an example of formatting numbers in currency.

First, we have the field in template with a small change to include filter.

<!-- displayData.vue -->
<template>
  {{ cost_amount | formatAmt }}
  <!-- output: ₹1,00,567.50-->
</template>

Next, define filter in <script>.

<!-- displayData.vue -->
<script>
  export default {
    data() {
      return {
        cost_amount: 100567.5
      };
    },
    filters: {
      formatAmt: function(value) {
        if (value) return 0;
        else
          return Number.parseInt(value).toLocaleString("en-IN", {
            style: "currency",
            currency: "INR"
          });
      }
    }
  };
</script>

Any number will now be displayed in INR on the UI - e.g. ₹1,00,567.50.

comments powered by Disqus