Home > Mobile >  What are the proper steps to include and use moment in Vuejs?
What are the proper steps to include and use moment in Vuejs?

Time:12-23

I'm trying to call moment() in my Vuejs application, I've tried declaring it like so :

methods: {
  moment: function () {
    return moment();
  }
},

and tried to my test it like so :

beforeMount() {
    console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
},

I kept getting

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

Do I need to add a moment to my package.json and run yarn install?

I would like to make it as light as possible since I will only need to access moment() only one page of my application, I rather not load them on all pages.

Please kindly suggest

CodePudding user response:

First you should install using the following commande :

npm i moment --save

then in your component import it and use it like :


import moment from 'moment/moment';

export default{

...
beforeMount() {
    console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
}

}

CodePudding user response:

Since moment is a deprecated lib (due to mutablility) also huge library in term of size , it's recommended to use other modern library sush dayjs, which is only a 2kB fast library that offers same functionality as moment

You could install it

npm install dayjs --save

then in your project (use specific plugin days js to show your specific format Do )

import advancedFormat from 'dayjs/plugin/advancedFormat';

export default{

...
beforeMount() {
    dayjs.extend(advancedFormat) // use plugin
    console.log(dayjs().format('MMMM Do YYYY, h:mm:ss a'))
}

See sample snnipet in pure js :

dayjs.extend(dayjs_plugin_advancedFormat);

console.log(dayjs().format('MMMM Do YYYY, h:mm:ss a') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.7/dayjs.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.10.7/plugin/advancedFormat.min.js"></script>

  • Related