How to use moment js in Vue component

4 different ways to use moment js in a Vue component.

How to use moment js in Vue component

Moment.js, also known as the Swiss Army knife for working with dates in JavaScript is definitely a  must have javascript library when you have to deal with different dates in your website.

There are different ways to use moment js in a Vue component.

We can use moment js in a Vue component in 4 different ways.

  1. As a vue method
  2. Using vue prototype
  3. As a computed property
  4. Using vue filters

Let us learn how to use each of these

1. As a Vue method

In this method you will directly import moment js in your vue component and use it as a method.

<template>
  <div>
    <span>{{moment(date).format('YYYY-MM-DD')}}</span>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  methods: {
    moment
  }
}
</script>

Note: If you are unaware following two are same

export default {
  methods: {
    moment
  }
}
export default {
  methods: {
    moment : moment
  }
}

2. Using Vue prototype

Using Vue prototype you can directly use moment in all of your components

In main.js

import Vue from 'vue'
import moment from 'moment'
Vue.prototype.moment = moment

Then in any of your component

<template>
  <div>
    <span>{{moment(date).format('YYYY-MM-DD')}}</span>
  </div>
</template>

3. As a computed property

<template>
  <div>
    <span>{{formattedDate}}</span>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data() {
    return {
      date: new Date()
    }
  },
  computed: {
    formattedDate() {
      return moment(this.date).format('YYYY-MM-DD')
    }
  }
}
</script>

4. Using Vue filters

Vue filters is my preferred way of using moment js.

<template>
  <div>
    <span>{{date | formattedDate}}</span>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data() {
    return {
      date: new Date()
    }
  },
  filters: {
    formattedDate(value) {
      return moment(value).format('YYYY-MM-DD')
    }
  }
}
</script>

You can use Vue filters to show different type of dates

<template>
  <div>
    <span>Published on : {{new Date("07-12-2016") | timeDate}}</span>
    <span>Last updated : {{new Date() | timeAgo}}</span>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  filters: {
    timeDate(value) {
      return moment(value).format('YYYY-MM-DD')
    },
    timeAgo(value) {
      return moment(value).fromNow()
    }
  }
}
</script>

In the example the output will be something like this

Published on : 2016-07-12 Last updated : a few seconds ago

As you can see, the publish date will be shown in "YYYY-MM-DD" format but the updated date will be shown as seconds/minutes/hours/days ago.

That's it. Let me know me in the comments which is your preferred way of using moment js in vue js.

Sponsored