Reputation: 4131
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?
Upvotes: 4
Views: 21375
Reputation: 1176
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' );
}
}
Upvotes: 1
Reputation: 344
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>
Upvotes: 1
Reputation: 4131
Finally, it works!
callmoment()
from inside Component's methods
block.
Sample usage:-
<template>
<v-ons-page>
<p>{{isToday("12-02-1980")}}</p>
</v-ons-page>
</template>
<script>
import moment from 'moment'
export default {
methods: {
isToday(date) {
return moment(date).isSame(moment().clone().startOf('day'), 'd');
},
}
}
</script>
Upvotes: 14