site icon

Hi, I’m Chris

I am a web developer teaching
regular people how to code

~ Welcome to my blog ~

Using global Vue filters with NUXT

nuxt global filters picture

When starting out with the NUXT framework for vue, you may be wondering where to add global filters. With a regular Vue.js project, we would typically add to it the main.js file.

NUXT has a different file/folder structure than a regular Vue.js application, Create-nuxt-app also creates a lot of Javascript files, so where do we add global filters?

The first thing to note here is that filters need to be loaded before our app starts so they are available to use in our components.

With NUXT, we can achieve this by creating a plugin. Plugins can be any simple custom Javascript code, or an external library/module, which we want to load before the root Vue.js app.

In our NUXT project, we will have a plugins folder, inside of here we can create a new file called filters.js.

In the filters.js file, as you may have guessed, is where we can add our filter code, don't for get to import Vue too:

// plugins/filters.js

import Vue from 'vue'
import moment from 'moment'

Vue.filter('formatDate', value => {
	if (!value) return ''
	return moment(value).format('LL');
})

This is an example filter to format the date using the moment.js package. But, you can add any filter code in here you want to use.

Next, we need to add this to our plugins key in the nuxt.config.js file. This file is where we can override default configuration for our NUXT project:

// nuxt.config.js 
  
plugins: ['~plugins/filters.js']

Make sure the above code is wrapped inside of the files export default, and you are good to go. You can now use the filter inside of you components as with a regular Vue.js app:

<span>{{post.date | formatDate}}</span>

- By Chris Dixon

Chris Dixon is a web developer and teacher. Teaching thousands of students mainly in Vue.js React.js, WordPress and web development.