Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Register Vue.js Filters as Plugins in Nuxt

    John LindquistJohn Lindquist

    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.

    vueVue.js
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss