⚠️ This lesson is retired and might contain outdated information.

Register Vue.js Filters as Plugins in Nuxt

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 4 months ago

Vue.js filters need to run before your app starts. In Nuxt, you do this by adding the filter as a plugin then registering it with your nuxt.config.js. This lesson walks you through create a date filter to better visually format the time.

To change this timestamp to a human readable time, we'll go ahead and add a filter inside of our plug-ins directory. Let's call this file filters.js.

I want to install - something to help me out here -- called date dash functions. This filter is essentially going to say, give me view, give me this function that I need from date functions, and the function I want is distance in words to now.

Because this is a plug-in, I can do things like view filter which run before a project runs. We'll call this filter time since, and this passes in the timestamp. We'll convert this first timestamp from [inaudible 0:49] in seconds.

We need it milliseconds, so this simple conversion here is just...I can show this is a number first, and times by 1,000 to change seconds into milliseconds. Then, we can simply return distance in words to now and pass in the time.

Right now, this filter isn't doing anything. We need to wire it up in the config, so we'll say plug-ins, which is an array, and just link to that filters. Once that set up, I can go into the component and back up to the time, and use it as the filter, so time since.

You can see that right away this turn to about four hours, about five hours. I go to new, I'll be newer less than a minute, two minutes. Just going to add the word "ago" just to make it more readable, so less than a minute ago, three minutes ago, five minutes ago, and we have our time filter up and running.

Rou Hun Fan
Rou Hun Fan
~ 6 years ago

what editor is this? I'm wondering how you're geting the full list of functions within date-fns

Christopher Hall
Christopher Hall
~ 4 years ago

For anyone else following along, with the release of v2.0 of the "date-fns" module, the distanceInWordsToNow function was deprecated. You will want to use the formatDistanceToNow function instead.

In fact, you can use the addSuffix: true option to automatically add a prefix or suffix, such as DATE ago or in DATE. formatDistanceToNow(time, {addSuffix: true})

Josh Ellis
Josh Ellis
~ 4 years ago

For anyone else following along, with the release of v2.0 of the "date-fns" module, the distanceInWordsToNow function was deprecated. You will want to use the formatDistanceToNow function instead.

Appreciate this

Markdown supported.
Become a member to join the discussionEnroll Today