Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: _vm.moment is not a function in Vuejs

I have a problem migrating to moment on Vuejs.

After running npm install vue-moment and adding to my script:

<script>

  const moment = require('vue-moment');
...
</script>

I added this into my <template> :

<h1>{{moment('2017-12-20 11:00').fromNow()}}</h1>

And I get this error:

[Vue warn]: Error in render: "TypeError: _vm.moment is not a function"

like image 963
Philx94 Avatar asked Oct 20 '25 01:10

Philx94


1 Answers

You can use it globally as @red-X said, but you can add it only on your component:

import moment from 'moment'

export default {
   data: () => ({
      moment: moment
   })
}

And then you can access it in your HTML template.

But i recommand you to use computed vars for using this kind of code, and to not have logic in your html template, just render computed vars inside your templates for readability.

And with this solution, you don't need to have moment library available globally or in your component, just the import.

Here it's an example :

import moment from 'moment'

export default {
   computed: {
      distanceFromNow() {
         return moment('2017-12-20 11:00').fromNow()
      }
   }
}

And in your template :

<template>
   <div>
      {{ distanceFromNow }}
   </div>
</template>
like image 73
jtouzy Avatar answered Oct 22 '25 07:10

jtouzy