What is the best way to implement momentJS globally in VueJS 2?

Currently working with Vue.js version 2.6.11

Trying to set up in main.js as follows:

import moment from 'moment'
moment.locale('nl');
Object.definePrototype(Vue.prototype, '$moment', { value: moment });

Encountering an error:

Uncaught (in promise) TypeError: Object.definePrototype is not a function

Attempted another approach:

moment.locale('nl')
Vue.prototype.$moment = moment

However, when running the page, receiving an error in console:

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

Importing moment from 'moment' directly in the Vue component works fine. However, looking to include it globally.

Any suggestions on how to resolve this issue?

Note that my Vue component looks like this:

<template>
<b-card no-body>
    ...
      <p class="mb-0 text-muted">{{formatDate(data.date)}}</p>
    ...
</b-card>
</template>

<script>
import moment from 'moment'
export default {
    props: ['data'],
    methods: {
        formatDate(date) {
            return this.$moment(date).format('YYYY MM DD')
        },
    },
}
</script>

Answer №1

Here is a helpful code snippet for you to try out.

import Vue from "vue";
import moment from 'moment'
moment.locale('de');
Vue.prototype.moment = moment;

You can now use the `moment` library directly in your component like this:

<template>
<b-card no-body>
    ...
      <p class="mb-0 text-muted">{{formatDate(data.date)}}</p>
    ...
</b-card>
</template>

<script>
export default {
    props: ['data'],
    methods: {
        formatDate(date) {
            return this.moment(date).format('YYYY MM DD')
        },
    },
}
</script>

Answer №2

It appears that you have a syntax error in your code. The correct function to use is Object.defineProperty or Object.defineProperties, not Object.definePrototype.

Please update your code from:

Object.definePrototype(Vue.prototype, '$moment', { value: moment });

to:

Object.defineProperty(Vue.prototype, '$moment', { value: moment });

Both of these define methods should work without any issues.

Object.defineProperty(Vue.prototype, '$moment', { value: moment });

// or 

Vue.prototype.$moment = moment;

Since the code snippet provided is minimal, it's difficult to pinpoint why $moment is not working for you precisely.

My guess is that you are trying to access this.$moment within the data() method?

A helpful tip: Avoid using this in data(), as the component might not be mounted yet. Consider using it in the mounted or methods section instead.

If you want an easier way to utilize this.$moment, consider importing the `vue-moment` package found here. This package already defines $moment, so all you need to do is import it and add Vue.use(require("vue-moment")); in your main.js file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to trigger a Quasar dialog from an outside component?

Currently, I am working with Vue.js 2.x + Quasar 1.x using http-vue-loader (no build tools required). I have placed a q-dialog in a separate component named MyComponent. However, when I try to include it in a parent component like this: <my-component&g ...

Provide details on the final parameters

After creating my discord.js bot, I had the idea to implement a translator feature. To achieve this, I need to extract the last argument from incoming messages. client.on("message", async (message, args) => { if (message.content.startsWith(` ...

Using AJAX, JQuery, and PHP to convert a given name to match the columns in a query, utilizing the data sent

One thing that I'm wondering about is how PHP handles my ajax requests. For example, consider the following code snippet: $("#addUser").on('click', '.btnAddSubmitFormModal', function() { $.post("add.php", { ...

Illumination causes surfaces to transform

In my simple scene, I have a ground and an interesting light source. However, when the light hits certain meshes, it creates some strange effects. The shadows are being cast correctly, but the other meshes affected by the light are showing unusual results. ...

Conceal a form depending on the referer_url parameter

I am looking to customize my 404 page by displaying a small form only when the visitor comes from a website, not from an email link or directly entering the URL. The purpose of this form is to address broken links that led the visitor to the error page. If ...

When a global variable is defined after a return statement within a function declaration, it does

Check out this Javascript code snippet: http://jsfiddle.net/ramchiranjeevi/63uML/ var foo = 1; function bar() { foo = 10; return; function foo() {} } bar(); console.log(foo); // should return 10, but returns 1 It's interesting to no ...

How to effectively delete the class from a navigation list item

Looking for some inspiration? Check out the basic visuals for this question here. But let me break it down for you. This snippet shows the HTML & CSS behind a tabbed-carousel, with a condensed version for clarity: <style> #myCarousel-100 . ...

Is there a way to disable page prefetching for Next.js Link when hovering over it?

Whenever a link is hovered over in my production application, an XHR request is sent to the server. I need to find a way to prevent this from happening. I tried using prefetch={false} but it didn't work. Any suggestions on how to resolve this issue? ...

React.js: Why does the array index change after dropping an element?

When I create a table with items in a checkbox list, the issue arises; after selecting and submitting some items, the index of the remaining items changes. Consequently, re-submitting the remaining items becomes impossible. Below is my code snippet: expo ...

Can a person select a characteristic like "height" using Javascript?

Is it doable to set a height for an image in CSS, then detect this gradient using JS and double the width based on the height x2.25? Could this be achieved? ...

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...

What are the steps to implement an audio stream in a JavaScript React application?

I have been working on integrating a web dialer system into my JavaScript NextUI React app. After making some progress, I can successfully dial and hear my voice through the phone. However, I am encountering an issue where I cannot hear the other person sp ...

The attempt to execute 'removeChild' on 'Node' was unsuccessful because parameter 1 is not the correct type. Although it did remove the elements from the DOM, it only did so once

It's quite a challenge I'm facing!!! Although there have been similar questions asked before, they were all for specific scenarios. I am currently developing a tictactoe game using the module design pattern. The function below helps me create tw ...

Setting default data in a data table that spans multiple pages is a useful feature that can

I am facing an issue with the default settings in the data table where I need the checkbox to be pre-checked on the controller's side. The problem arises when the checkbox is not staying checked after navigating to the second page and beyond. functi ...

The CSS transition duration is not being applied properly on the initial transition effect

Looking to create a dynamic set of sliding divs that can be triggered with the press of a button. Each div will contain a thumbnail image and accompanying text. The goal is to enable the user to navigate through the content by clicking the left or right bu ...

At what point are DOMs erased from memory?

Recently, I've been working on an application that involves continuous creation and removal of DOM elements. One thing I noticed is that the process memory for the browser tab keeps increasing even though the javascript heap memory remains steady. To ...

Is there a way to extract dates from multiple date pickers using Vuetify?

Here is the script I'm working on: <template> <v-container> <v-dialog v-for='foo in foos' :key='foo.id' :close-on-content-click="false" transition="scale-transition" ...

Is there a missing X-AppEngine-Region in the headers of the AppEngine application?

I've been trying to access the Region and Country in my request, but it seems like the X-AppEngine-Region and X-AppEngine-Country headers are missing. Sometimes I see headers like alt-svc content-length content-type date etag server status via ...

Having trouble deploying Vue files correctly in conjunction with a Django backend implementation

Check out my Brain Teasers site on GitHub A unique Vue (with vue cli) and Django application deployed to Heroku. While everything functions perfectly on the local machine during development, there seems to be an issue with the static file request path for ...

Could it be feasible to manage several ongoing asynchronous requests simultaneously?

Visualize a grid in which the user completes cell A1 and presses Enter to move to A2. As this happens, a request is sent to the backend to search a database and retrieve results for populating the remaining cells in row A. Meanwhile, I want the user to con ...