TypeError: _vm.moment is not a function in Vuejs

Viewed 11703

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"

4 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>
import * as momentTemp from 'moment';
const moment = momentTemp["default"];

Did you add the 'moment' attribute to the lifecycle 'methods',forExample:

methods:{ moment, function a(){}, }

Did you add moment to the global Vue object like this:

const moment = require('vue-moment');
Vue.use(moment)

Just adding it to the local scope of a component will not make it available for use in the template. Everything referenced in the template is taken from the component itself.

Related