Getting Started with Filters in Nuxt 2

19/05/2020

Filters are a great functionality to apply text formatting and transformation to a value in Vue/Nuxt

I’ve been working on Vue for almost a couple of years now and always wanted to explore and build something using Nuxt. So I was building an app that had a feature to change currency and based on the selected currency I wanted to show the currency symbol with all the currency values throughout my application. In this post, I’m going to share my learning on how to implement Filters in our Nuxt app.

Anyone with a basic knowledge of Vue/Nuxt should be able to pick up things very easily.

What are filters and how to use them

Filters in Vue are a functionality to apply text formatting and transformation to a value. For e.g., ‘elon’ can be converted into ‘Elon’ by creating a capitalize filter. Filters can be used in mustache interpolations and v-bind expressions(I prefer using them inside the mustache interpolations, as it looks more cleaner to me this way).

Implementing our first filter

We all have dealt with currencies at some or the other point in frontend development. So creating a currency filter that will show a currency symbol before a number would a good option, like for e.g. it will convert 100 to $100. Implementing Filter in a Nuxt app is very similar to any Vue app.

  1. Create a new Nuxt project using create-nuxt-app command(we can simply choose all the defaults while setting up the project).

    npx create-nuxt-app
  2. Now create a new file in the plugins folder and name it currency.js.

  3. Next lets import Vue in the new file and define our filter.

    import Vue from 'vue'
    
    export default () => {
      Vue.filter('currency', function (value) {
         if (!value) return ''
         return `$${value}`
      })
    }

Here the ‘currency’ is the name of our filter, value is the expression’s value and inside the function is the logic for it.

  1. For the final step we just need to add our filter to the plugins array inside the nuxt.config.js file, this will help us to use our filter globally throughout the app.

    plugins: ['@/plugins/currency.js']
  2. It’s done. Now we can easily use the currency filter in any of our components. Just add the name of the filter(currency in our case) with the pipe symbol inside the mustache interpolations(curly brackets).

    {{ '100' | currency }} // will be rendered as $100

Edit global-filter

Conclusion

In this post, we’ve learned how to build our own global filter in Nuxt from scratch. Similarly, we can create any other filter like capitalize(for capitalizing the first character of String), etc. and use it as per our use case.

Read official doc for more info.

This is my first post, feedback would be highly appreciated. Feel free to share and reach out to me on twitter.

Thanks! 🙏