In your main js file do like this. window.moment = require('moment');
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 :)
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 :)
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..
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 }}
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.
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.
@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.
@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);
}
}
// ...
I have managed to use momentJS globally.
- Require moment in your main.js -> var moment = require('moment');
- 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.
@FRANCISMORI7 - clever idea it helps me in a quasar project, thanks
fwiw, there are other as capable libraries as moment that are smaller... if you care about your js bundle size (which you should)
Please or to participate in this conversation.