Global Filter Using MomentJs In Vue3

Dami Sparks
Nerd For Tech
Published in
2 min readJul 28, 2021

The article demonstrates how to implement a global filter for momentjs in your Vue3 application. This demo use Vue3 version 3.x

First things first, I won’t be covering how to develop your application using Vuejs and moment. I am assuming you already how to do that. If you don’t, I highly recommend checking their documentation. I have provided the link below.

Vuejs -Progressive Javascript Framework Guide

That said, Let’s get to the fun part. You should follow the steps in the article to achieve a similar result.

Implementation Steps

  • install the momentjs in your package.json
npm install moment --save
  • import moment into your main.js file
import moment from 'moment'
  • check if your configuration is like this and comment it out
// createApp(App).use(router).use(store).mount(‘#app’)
  • add the new configuration
// createApp(App).use(router).use(store).mount('#app') // remember you already commented this out.
const
app = createApp(App)
/*** @params {date} date to be converted to timeago* @returns returns timeAgo*/app.config.globalProperties.$filters = {timeAgo(date) {return moment(date).fromNow()},}app.use(router).use(store)app.mount('#app')
  • The new configuration is the same as before, just with a slight modification of adding the filter.
  • To test it out, try the below code
<p>{{ $filters.timeAgo(Date.now()) }}</p>
<!-- expected output : a few seconds ago -->
  • Remember, your filter is available globally

If you get the same output, congratulations 🥳; if not, go through your steps again.

In addition, I have provided my code below.

NOTE

The momentjs is in legacy mode and now in maintenance mode. In most cases, you should choose a different library. The same logic applies.

Let me if there is anything that is not clear or you have doubts.

Thank you for reading.

--

--

Dami Sparks
Nerd For Tech

Software Engineer with an eye for design | Let’s get in touch 👉 linkedin.com/in/damisparks