How to create filters in NuxtJS

Filters are reusable code for text formatting, It can be used in mustache interpolations and `v-bind` expressions.

How to create filters in NuxtJS
How to create filters in NuxtJS

Filters are reusable code for text formatting, It can be used in mustache interpolations and `v-bind` expressions.

const price = 4000;
<!-- in mustaches -->
{{ price | currency }}

<!-- in v-bind -->
<div v-bind:id="price | currency"></div>
Filters are like pipe functions in Javascript

Create currency filter

import Vue from 'vue'

Vue.filter('currency', function (value, currency = 'INR') {
    return new Intl.NumberFormat("en-IN", {
        style: "currency",
        currency,
    }).format(value)
});

Vue.filter accepts two arguments, name of the filter and callback function that returns  currency formatted text.

<!-- in mustaches -->
{{ price | currency('USD') }}

Returns currency in USD format

<!-- in mustaches -->
{{ price | currency('INR') }}

Returns currency in INR format

Capitalize filter

import Vue from 'vue'

Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})
<!-- in mustaches -->
{{ lowercaseText | capitalize }}

Filters can be used as pipe/chain like {{ text | capitalize | highlight }}

capitalize accepts text as first arguments and returned value for capitalize will sent to highlight filter.

Conclusion

We have see how to create filters in Nuxt JS. Filters are very powerful, it should be used wisely or it could impact the performance of the application.
Happy Coding!!!