Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use moment library inside a Vue.js component

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?

like image 205
user1 Avatar asked Dec 03 '22 21:12

user1


2 Answers

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>
like image 116
user1 Avatar answered Jan 09 '23 21:01

user1


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>
like image 40
seagulledge Avatar answered Jan 09 '23 21:01

seagulledge