How to use moment library inside a Vue.js component

Viewed 19539

After, yarn add moment

I tried...

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

&

import moment from 'moment'
Vue.use(moment)

&

var moment = require('moment');
Vue.use(moment)

Nothing really works. I am getting all kinds of weird error msgs!

Can anyone tell, how to use moment library with Vue.js 2?

3 Answers

I found that when using TypeScript, it was necessary to use

import * as moment from 'moment'

Sample:

<template>
<div id="sample">
    <span>{{ formatDate("11-11-2011") }}</span>
</div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Component } from 'vue-property-decorator'
import * as moment from 'moment'

@Component()
export default class Sample extends Vue {

    formatDate(d) : string {
        return moment(d).format("MMM Do YYYY");
    }
}
</script>

I didn't want to import Moment in every vue component, so I went with an approach that is described in this article: https://vuejsdevelopers.com/2017/04/22/vue-js-libraries-plugins/

import Moment from 'moment';
Moment.locale( 'de' );
Object.defineProperty( Vue.prototype, '$moment', { value: Moment });

Now you can use Moment in your components, ie.:

   methods : {

        date : function( timestamp ) {

            return this.$moment( timestamp ).format( 'LLL' );

        }

    }
Related