Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is moment js not working in mounted vue component?

When I put moment on the method like this:

<template> 
    ...
</template>
<script>
    export default{
        ...
        methods:{
            ...
            add(event){
                let current = moment()                  
            }
        }
    }
</script>

and then call the add method, it works without error.

But if I put moment on the mounted like this:

mounted(){
   let currentAt = moment()   
}

it does not work. It returns the following error:

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

How can I solve this?

like image 429
moses toh Avatar asked Sep 19 '25 15:09

moses toh


2 Answers

Since you are using .vue files, I am assuming you are using the vue-loader or some other loader within the webpack ecosystem. If you are, then you can do something like the following:

<script>
 export default{
    import moment from 'moment'
    ...
    methods:{
        ...
        add(event){
            let current = moment()                  
        }
    }
}
</script>

Then, just make sure you either execute yarn add moment or npm i -s moment.

like image 90
miguelsolano Avatar answered Sep 22 '25 07:09

miguelsolano


If you make a bundle, at the beginning of script, you need to import moment from 'moment'.

If you import the files in your HTML, put a script tag in the HTML:
<script src="moment.js"></script>.

like image 36
François Romain Avatar answered Sep 22 '25 06:09

François Romain