TypeError: _vm.moment is not a function in Vuejs
Asked Answered
F

4

5

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"

Flyer answered 11/10, 2019 at 13:16 Comment(0)
C
10

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>
Capitulary answered 11/10, 2019 at 13:28 Comment(0)
I
0
import * as momentTemp from 'moment';
const moment = momentTemp["default"];
Inion answered 4/5, 2020 at 15:24 Comment(1)
This may be a correct answer, but it’d be useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who may not be familiar with the syntax. Further, it can help reduce the need for follow-up questions. Would you mind updating your comment with additional details?Hilten
G
0

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

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

Gunstock answered 16/6, 2022 at 9:42 Comment(0)
F
-1

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.

Finsen answered 11/10, 2019 at 13:21 Comment(1)
I just did. But now I get: Error in render: "TypeError: vue_moment__WEBPACK_IMPORTED_MODULE_0___default(...) is not a function"Flyer

© 2022 - 2024 — McMap. All rights reserved.