Home > database >  How can I using momentJS globally in VueJS 2?
How can I using momentJS globally in VueJS 2?

Time:08-22

I use vue js version 2.6.11

I try to set up in main.js like this :

import moment from 'moment'
moment.locale('nl');
Object.definePrototype(Vue.prototype, '$moment', { value: moment });

But there exist error :

Uncaught (in promise) TypeError: Object.definePrototype is not a function

I try another way like this :

moment.locale('nl')
Vue.prototype.$moment = moment

But when I run the page, on the console exist error :

[Vue warn]: Error in render: "ReferenceError: moment is not defined"

If I put import moment from 'moment' directly in component vue, it works. But I want to put it globally

How can I solve this problem?

Note :

My component vue like this :

<template>
<b-card no-body>
    ...
      <p >{{formatDate(data.date)}}</p>
    ...
</b-card>
</template>

<script>
import moment from 'moment'
export default {
    props: ['data'],
    methods: {
        formatDate(date) {
            return this.$moment(date).format('YYYY MM DD')
        },
    },
}
</script>

CodePudding user response:

You have wrong syntax. There's no Object.definePrototype, the function you need is Object.defineProperty or Object.defineProperties

Change your code

Object.definePrototype(Vue.prototype, '$moment', { value: moment });

to

Object.defineProperty(Vue.prototype, '$moment', { value: moment });

Both define methods work fine for me.

Object.defineProperty(Vue.prototype, '$moment', { value: moment });

// or 

Vue.prototype.$moment = moment;

Since the less code, I can not point out accurately why you can not use $moment.

But, I guess you use this.$moment in data() (?)

Tips: You can't use this in data(), since the component isn't mounted yet. Try to use it in mounted or methods section.

Also, the easiest way to use this.$moment, just import the package vue-moment here. This package already define $moment. All you need to do is import it and type Vue.use(require("vue-moment")); in your main.js.

CodePudding user response:

You can try the following. In main.js

import Vue from "vue";
import moment from 'moment'
moment.locale('de');
Vue.prototype.moment = moment;

And in your component you can directly use moment as below

<template>
<b-card no-body>
    ...
      <p >{{formatDate(data.date)}}</p>
    ...
</b-card>
</template>

<script>
export default {
    props: ['data'],
    methods: {
        formatDate(date) {
            return this.moment(date).format('YYYY MM DD')
        },
    },
}
</script>

CodePudding user response:

i think its better to use vue-moment see the link blow:

https://www.npmjs.com/package/vue-moment

  • Related