This page looks best with JavaScript enabled

Format Data Using Vue Filters

 ·   ·  ☕ 1 min read

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.

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

Next, define filter in <script>.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<!-- 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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things