Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nathandunn's avatar

Moment.js with Vue

Hi,

I was wondering if anyone has any experience integrating Moment.js into Vue, I am building a component-based system with Vueify and would like a way of pulling in Moment without having to require it every time. Has anyone had any experience of doing this?

Thanks :)

0 likes
12 replies
stevemo's avatar

In your main js file do like this. window.moment = require('moment');

3 likes
nathandunn's avatar

Hi @stevemo, thanks for your reply.

I have done what you have told me and have tried to run the following piece of code:

{{ window.moment(message.timestamp).format("DD-MM-YYYY [at] hh:mm") }

I seem to be getting the error:

Uncaught TypeError: scope.moment is not a function.

Am I doing something wrong here?

Thanks in advance :)

1 like
colourmill's avatar

In my experience there's no need to require it. I just bundle it in my vendor.js file and I can use it in all of my components..

stevemo's avatar

I've just tried like you did and in fact it didn't work. It is working if you use computed property or a method.

in your component try this

computed: {
    timestamp: function() {
        return moment(this.message.timestamp).format("DD-MM-YYYY [at] hh:mm")
    }
}

then in your html {{ timestamp }}

Francismori7's avatar

I ended up creating methods in my components to use moment() because I can't find any way to use functions out of the scope vue provides/forces you to use.

tam5's avatar

I just found this thread.

Here's what I did to make it work:

var moment = require('moment');

new Vue({
    el: '#vue',

    data: {
        moment: moment
    },
// etc...

And I am using elixir's browserify to mix the script so that we have require.

2 likes
Codeus's avatar

@Tam, you don't need to to initialize moment property of the data object at all. Fist line of your code block is enough - just call moment() wherever you need.

Francismori7's avatar

@codeus, you missed the point. You can't use global scope variables from Vue's template bindings like this:

{{ moment(user.created_at).fromNow() }}

Having moment in the data helps. My way is to do this:

    //...
    methods: {
        moment(...args) {
            return moment(...args);
        }
    }
    // ...
4 likes
abhimmit's avatar

I have managed to use momentJS globally.

  1. Require moment in your main.js -> var moment = require('moment');
  2. Maak moment as a Vue prototype -> Vue.prototype.$moment = moment;

Now you can use moment throughout your project without requiring it again like this; this.$moment(...).format(..)

Hope this helps.

Please or to participate in this conversation.