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

Personalized modify and remove elements on a row of the DataGrid material-ui version 5 component when hovered over

In my React Js app, I am utilizing Material UI components or MUI v5 as the UI library for my project. Within the DataGrid/DataGridPro component, I am implementing a custom edit and delete row feature. The requirement is to display edit and delete icons w ...

Exploring the power of Vue by processing components on a local

I have come across this code: <my-messages> <message>Hello</message> <message>World</message> </my-messages> Currently, my <my-messages> component is rendered as: <div class="Messages"> <!-- ...

VueJS Vuetify automatically centers default content

Vue cli version @ 5.0.6 | Vuetify version: [email protected] I have been utilizing Vue.js and Vuetify for some time now, and I can't shake the feeling that not all Vue.js/Vuetify components default to centered alignment. I recently initialized a ...

Is there a way to determine whether a mouse-down event took place on the scroll-bar or elsewhere within the element?

Looking for a solution with my HTML div acting as a canvas containing various objects. The issue lies in the fact that when attempting to draw a selection rectangle by dragging with the mouse, if scroll bars appear due to the large size of the canvas, scr ...

Error message: NGINX combined with Express.js and socket.io, page not found

I currently have a node/express.js/socket.io application set up on an Ubuntu Server running on port 3002. I've made sure to open all ports on the machine for accessibility. When accessing the app directly at 11.111.111.1:3002/, everything runs smooth ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

My CSS seems to be causing an issue and preventing the function from running correctly. Now I just need to

I'm currently working on a project and following a tutorial to help me create a navigation bar. The tutorial I am using can be found here: https://www.youtube.com/watch?v=gXkqy0b4M5g. So far, I have only reached the 22:05 mark in the video. I have su ...

Navigating between Vue Router pages triggers multiple events within the mounted() lifecycle of VueJS

Currently, I am immersed in a project using Electron with a Vue CLI setup and the Vue CLI Plugin Electron Builder. The overall functionality is working perfectly fine except for a peculiar bug that has recently surfaced. The issue arises when navigating b ...

Utilize Javascript/Jquery to categorize JSON data based on the days of the week (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

A function is provided below that retrieves data for a chart. The output produced by this function is structured as follows: [Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, vo ...

Guide to dynamically updating a textarea in vue.js by incorporating data from several inputs

Is there a way to update a textarea based on multiple inputs using jQuery and vue.js? I have successfully implemented the jQuery part with line breaks, but when I try to display the value of the textarea elsewhere using vue.js, it doesn't seem to work ...

React Component: Issue with conditional "if else" statement not refreshing in return statement

Starting out in React and the front-end field with minimal experience. Currently attempting to dynamically change the color of the "fill" property in a polygon element using React. If the percentage is greater than 50, I want the color to be green; otherw ...

Gathering feedback from a webpage using JavaScript and jQuery

I have been experimenting with different tools such as Selenium and BeautifulSoup in an attempt to scrape the contents of the following website/pages: . Specifically, I am looking to extract the reviews/sections which are dynamically loaded by JS, jQuery ...

Issue with MVC framework: AJAX query callback function not functioning properly

Struggling with implementing a basic Jquery Ajax callback: Here is my Jquery code snippet: $(document).ready(function () { $('#btnClient').click(function (e) { e.preventDefault(); var txtClient1 = $('#txtCli ...

Building a promotional widget

I'm currently working on developing an ad widget that can be easily reused. I'm debating whether to use jQuery or stick with pure JavaScript for this project. What are your thoughts on the best approach for creating a versatile and efficient ad w ...

Utilize Element UI autocomplete to transfer data into a VueJS-powered table's input fields

I am currently working on designing an invoice form using the Element UI framework. I have successfully integrated an autocomplete feature that retrieves data from the loadAll array. Upon clicking the add button and selecting an item_name from the autocomp ...

There is an absence of the 'Access-Control-Allow-Origin' header on the requested resource despite its existence

Currently, I am working on developing an application using Django and Phonegap. While attempting to send an Ajax Request with the following function: <script> $.ajax({ url: "http://192.168.0.101/commerce/pro ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Adjust the position if the height exceeds 100 pixels

Can someone help with this code issue? $(document).ready(function () { if ($('.pi-img').height() > 100) { $(this).css('top' , '30%'); console.log('yeah'); } }); I am encountering difficu ...

Retrieve information from an express server using the fetch API

I am attempting to use the alert function to display a variable string in Express's .get() method and then send it using res. I want the alert to show "I am working fetch". This is my server.js var express = require('express'); var app = e ...

Responsive Bar Chart using jQuery Mobile and ChartJS that appears on the screen only after resizing

I have been experimenting with adding a responsive bar chart using Chart.js in one of my JQM projects. Here is what I have accomplished so far: http://jsfiddle.net/mauriciorcruz/1pajh3zb/3/ The Chart needs to be displayed on Page Two and it should be res ...