How to use Vue.js Filters in NuxtJS

Last updated at April 19, 2021

💬

I'll demonstrate configuration to use my 'formatDate' Vue.js filter in my NuxtJS project.

[Optional] install Day.js package from npm

Because I'll use Day.js to format date, I need to install package first.

bash
npm install dayjs --save

Create filters.js file to /plugins folder

All of my Vue.js filters are managed by filters.js file.

Add your filters in this file.

/plugins/filters.js
import Vue from 'vue'
import _ from 'lodash'
import dayjs from 'dayjs'

Vue.filter('formatDate', (value, format) => {
  return dayjs(value).format(format)
})

Vue.filter('startCase', (str) => {
  if (!str) return ''
  str = _.startCase(str.toString())
  return str
})

Register filters.js file to nuxt.config.js file

/nuxt.config.js
export default {
  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    "~plugins/filters.js"
  ],
}

Use registered filters in your vue file

xxx.vue
<div>{{ article.createdAt | formatDate('DD MMM, YYYY') }}</div>