4

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 4

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>
Sign up to request clarification or add additional context in comments.

Comments

0
import * as momentTemp from 'moment';
const moment = momentTemp["default"];

1 Comment

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?
0

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

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

Comments

-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.

1 Comment

I just did. But now I get: Error in render: "TypeError: vue_moment__WEBPACK_IMPORTED_MODULE_0___default(...) is not a function"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.