Discovering the method to retrieve a previous month's date within a VueJs application using Javascript

Can someone guide me on how to retrieve the date of the past month using Vue? This is the code I currently have:

import SomeTable from "./table/SomeTable";

export default {
    name: "Cabinets",
    components: {SomeTable},
    data() {
        return {
            defaultColumns: [
                'id',
                'serialNumber'
            ],

            defaultStartDate: new Date(),
            defaultEndDate: new Date('2019-10-07')
        }
    },
    props: {
        startDate: {type: Date, required: false},
        endDate: {type: Date, required: false},
    }
}

</script>

Next, upon placing defaultStartDate and defaultEndDate in the SomeTable element like this:

 <some-table :start-date="defaultStartDate" :end-date="defaultEndDate" :default-columns="defaultColumns"></some-table>

The output correctly displays today's start date along with the set end date. However, when attempting something like the code snippet below:

defaultEndDate: new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate()

I encounter errors in my local environment such as a blank screen and various issues. It seems that I'm unable to execute JavaScript in that specific context within Vue. As I am still learning about Vue and couldn't find much information through search engines, I would appreciate any advice on approaching this using either Javascript or if there's a specialized method in Vue.

EDIT: The errors I'm facing include messages like:

Error in data(): "TypeError: Date().getFullYear is not a function"

These errors arise with every JavaScript function I attempt to use inside Vue. Additionally, there's also an issue reporting:

Invalid prop: type check failed for prop "endDate". Expected Date, got String with value "2019-9-5".

Answer №1

When you define

endDate: {type: Date, required: false},
in your code, it indicates that endDate should be of Date type.

Therefore, you must ensure the calculated value is converted into a Date format like this:

defaultEndDate: new Date(`${(new Date()).getFullYear()}-${(new Date()).getMonth()}-${(new Date()).getDate()}`)

UPDATE: Don't forget to consider that the month January starts at 0. Using the above approach may lead to errors during January. It might be more practical to utilize a computed value as shown below;

computed: {
  defaultEndDate() {
     const now = new Date();
     now.setMonth(now.getMonth() - 1);
     return new Date(now.toJSON().slice(0, 10));
  }
}

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

Creating an Active Link in Bootstrap 5.0 (Beta 3) Navbar Using JavaScript

I am currently working with Bootstrap 5 (Beta 3 - no JQuery) on a static website, and I am facing the challenge of making a navbar link appear active. I prefer to achieve this using JavaScript instead of creating a separate navbar for each page. For instan ...

Utilizing NodeSize to Optimize the Spacing Among Nodes in the D3 Tree Arr

Currently, I am trying to adjust the positioning of my rectangle nodes because they are overlapping, as illustrated in the image below: In my research, I discovered that D3 provides a nodeSize and separation method. However, I encountered difficulties imp ...

What is the best way to make the Nav bar overlap instead of shifting content to the right?

Is there a way to open the nav bar and have it overlap on the right without pushing content to the right? I tried experimenting with position and z-index, but it didn't work. Thank you! Link <div id="mySidebar" class="sidebar" ...

Creating a unique field button in AngularJS that is dynamically generated and specifically targeted as the last button

Is there a way to enable the plusSign = true option only for the last item in the dynamic input field? (function() { var app = angular.module('managementApp', []); // var app = angular.module('managementApp', ['ngRoute' ...

Utilizing Vuetify's data-table to seamlessly integrate dynamic slots with row/item slots

My goal is to create a reusable vuetify datatable that allows for dynamic slot customization. The code snippet below demonstrates how this can be achieved: <v-data-table :headers="headers" :items="items" :dense="dens ...

Is there a way to locate an element within innerHTML using getElementById?

Is it possible to achieve the following code snippet? <div id="parent"> <iframe id="myFrame" title="HEY!" srcdoc="<div id='inner'>Hello World!</div>"></iframe> </div> v ...

The value of req.session.returnTo is not defined

I have implemented passport for user authentication using discord oauth2. I want the users to be redirected back to the original page they came from instead of being directed to the home page or a dashboard. Even though I tried saving the URL in the sessi ...

tips for extracting a specific attribute value from an XML document

Within my C program, I am working with the following XML data: <apStats><command chart_num="0">750</command><command chart_num="1">400</command></apStats> . $.ajax({ type: "POST", dataType: "xml", url: ge ...

The issue of Bootstrap dynamic tabs retaining their active state even after switching tabs, leading to elements being stacked

For my university project, I am developing a website that resembles a text editor using Bootstrap as the framework. To create the website menus, dynamic tabs have been utilized. The following is the code snippet I have implemented: <!--Bootstrap ...

Limit the option to check or uncheck all on the current page only

I am facing an issue with a select all checkbox that interacts with checkboxes in a paginated table. The problem arises when I check the select all box, as it selects all records instead of just those on the current page. For example, if there are 200 reco ...

A guide on how to implement promise return in redux actions for react native applications

I'm using redux to handle location data and I need to retrieve it when necessary. Once the location is saved to the state in redux, I want to return a promise because I require that data for my screen. Here are my actions, reducers, store setup, and ...

What is the best method to invoke a function recursively with a delay of 1 second following the completion of an ajax

I am facing a situation where I need to implement a delay of 1 second after an ajax request is completed, regardless of the outcome. Instead of calling a method every second, I specifically want to call a function 1 second after the ajax request finishes. ...

Executing a POST request with AJAX in jQuery to communicate across different domains and fetching XML data as

Is it possible to send an AJAX request using the POST method and receive XML as a response text? If so, please provide me with the steps to achieve this. For example: url : "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate" data ...

The PayPal checkout component in Vue remains in sandbox mode

I've been facing challenges when trying to transition to the live environment. It's perplexing how everything seems to function seamlessly in sandbox mode, yet there appears to be no clear guidance on switching to production or it simply doesn&ap ...

Can data be transferred from the template to the script using Vue.js? (Opposite of v-bind)

Is it possible to pass the current data in a v-for loop (in the template) to a function in methods? <li v-for="annonce in annonces"> <article> //For example, can I send annonce.categorie to the methods //object of the component t ...

How can data be shared among single file components in Vue files?

One issue I'm facing is that the data in my Topbar.vue file, specifically activeTab, is confined only to the Topbar.vue component. However, I need this value to interact with other components in my blade view. main-page-blade.php <div id = "app"& ...

Exploring the Possibilities of Utilizing Async Middleware for Error Handling in VueJS Router

Greetings, this is my inaugural question on Stack Overflow. For my Frontend, I am utilizing VueJS and for Backend, Laravel. My current predicament involves loading a model from the backend API that requires user editing. However, there are policies in pla ...

When scrolling, the fixed menu bar at the top of the page is making the content below jump

I am attempting to create a fixed submenu that sticks to the top of the page when scrolling, but I am encountering some issues. The current code I have is as follows: $(window).scroll(function () { if ($(window).scrollTop() > 175) { $('#loca ...

Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end. function findDateDifferences(obj1, ...

What are some ways to disguise websockets?

I'm currently working on writing a JavaScript client that sends websockets to a node.js/ws server. I've been doing a lot of research and have come across information indicating it's useful, or even required by RFC, to mask all data sent from ...