DEV Community

loading...
Cover image for Adding a Date Format Filter in Nuxt

Adding a Date Format Filter in Nuxt

wrrnwng profile image Warren Wong Originally published at warrenwong.org on ・2 min read

Since NuxtJS is just an opinionated VueJS with built in state management and routing, writing a filter for your template is just the same for Nuxt as it is for Vue, except for one catch. For now, let's start with a date formatter inside a component. Inside your component script tag, give the extends method your options object with a property of filters. Filter will be an object literal. The property names will be the name of the filter within the component. I don't really have any fancy formatting in mind, so let's just call this filter "formatDate". From a little bit of googling, I found the built in Intl.DateTimeFormat. This looks like it's exactly what we need. It seems to handle language specific formatting as well as time zones. I don't really need those yet, and I only write in English so I'm used to seeing the mm/dd/yyyy. For now, I think that's enough for me.

import Vue from "vue";
export default Vue.extend({
  filters: {
    formatDate: (date: Date) =>
      Intl.DateTimeFormat("us-EN").format(date),
  },
});
Enter fullscreen mode Exit fullscreen mode

One snag is that I'm using Nuxt Content and I want to show the createdAt string that the module provides based on when the markdown file was created. createdAt returns a date in the form of a string, so I'll have to update the filter to handle that directly.

import Vue from "vue";
export default Vue.extend({
  filters: {
    formatDate: (dateStr: string) =>
      Intl.DateTimeFormat("us-EN").format(new Date(dateStr)),
  },
});
Enter fullscreen mode Exit fullscreen mode

If we test that in the template, it seems to work just fine.

<template>
  <div>
    Date: {{ post.createdAt | formatDate }}
  <div>
</template>
Enter fullscreen mode Exit fullscreen mode

Now, this filter seems pretty useful. I'd think we would need this in a lot of
pages and components so we should make this filter available to all the
templates.

In plain Vue, you can just register the filter with Vue like so:

Vue.filter("formatDate", (dateStr: string) =&gt;
  Intl.DateTimeFormat("us-EN").format(new Date(dateStr))
);
Enter fullscreen mode Exit fullscreen mode

It's actually just the same in Nuxt, but we will be putting the filter in a
plugin that's registered in the nuxt.config.ts file.

In the /plugins directory, create a file called format-date.ts. We "plugins"
we put here are run before the root VueJS app gets instantiated.

import Vue from "vue";

Vue.filter("formatDate", (dateStr: string) =&gt;
  Intl.DateTimeFormat("us-EN").format(new Date(dateStr))
);
Enter fullscreen mode Exit fullscreen mode

If we check our prior rendered page, the filter should still work after the page hot reloads.

Discussion (0)

Forem Open with the Forem app