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

Automatically conceal a div or flash message after a short period of time by utilizing CSS3 in a React

I am relatively new to the React environment and recently created a basic component for a bookmarking feature. Essentially, when the favourite icon is clicked, an ajax call is sent > a record is created in the database > on ajax success, a flash me ...

Unclear when notifying div content

After creating a PHP page, I encountered an issue while trying to select the inner text of a div and alert it with jQuery. Instead of getting the expected result, it keeps alerting "undefined." What could possibly be causing this? Here is the code snippet ...

Is there a way to display the button just once in a map function while still retaining access to the iteration value?

Utilizing formik within material-ui for a form has been quite productive. I've implemented a map function to print text fields and managed to display the Submit button only once by targeting the index. However, there's an issue when attempting to ...

Is it possible to have nullable foreign keys using objectionjs/knex?

It seems like I'm facing a simple issue, but I can't quite figure out what mistake I'm making here. I have a table that displays all the different states: static get jsonSchema() { return { type: 'object', propert ...

Enhance Your Search Bar with Ajax and JQuery for Dynamic Content Updates

My goal is to create a search bar that dynamically loads content, but I want the actual loading of content to start only after the user has finished typing. I attempted a version of this, but it doesn't work because it doesn't take into account ...

Exploring the Possibilities of Automating Page Navigation with Vue-Router

What is the best way to automatically switch between two pages in a Vue.js application without any user interaction? I want to display the HelloWorld page first and then switch to the myPage page after a few seconds. I believe I need to use the vue-router ...

Utilizing Ajax: Sending Customized Data to a Modal

Having never worked with jquery before, I struggled to find a solution for my specific case. On the cockpit.php page, I have a form that retrieves content from a mysql database. Currently, I am able to display this content in a div on the same cockpit.php ...

Is it possible to use getJSON to retrieve a value from an HTML tag ID that has already been displayed on a webpage? How about using json_decode

Is there a way to retrieve the value using the HTML tag ID after an HTML page has been rendered? For example, how can I access the date value using the td_date in my JavaScript function? Below is the code snippet that populates the data on the page: listS ...

Data vanishing in upcoming authentication session in test environment

I have encountered an issue with next auth in my next.js project. During development, the session data is lost if the server refreshes or if I switch to another tab and return to it. This forces me to sign out and then sign back in to restore the session d ...

Unable to perform filtering on a nested array object within a computed property using Vue while displaying data in a table

Lately, I've been experimenting with different methods to filter data in my project. I've tried using various approaches like methods and watchers, but haven't quite achieved the desired outcome yet. Essentially, what I'm aiming for is ...

the language of regular expressions expressed in strings

As a beginner in Javascript and regular expressions, I found myself stuck on how to create a route that matches all URLs starting with /user/.... Initially, I thought of using app.get(/user/, function(req, res){ /*stuff*/}); However, curiosity led me to ...

Laravel 4 - Error: Uncaught TypeError - Unable to access property 'post' as it is undefined

Here is the script I am using: <script> function selectModSetProd(prodId,setId,objControl){ function ifOK(r){ objControl.style.background="'"+r.color+"'"; } function ifError(e){ alert( ...

how to prevent autoscrolling in an angular application when overflow-x is set to

In my socket event, I am using $scope.items.unshift(item) to place the new item at the top of the list. The html code includes <ol ng-repeat="item in items"><li>{{item.name}}</li></ol> An issue arises when a new item is added whil ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

ReactJS component's function become operational only after double tapping

Dealing with the asynchronous nature of react hook updates can be a common challenge. While there are similar questions out there, I'm struggling to find a solution for my specific case. The issue arises when trying to add a new product object into a ...

Clicking does not trigger scrollIntoView to work properly

I'm facing an issue with a button that is supposed to scroll the page down to a specific div when clicked. I implemented a scrollIntoView function in JavaScript and attached it to the button using onClick. Although the onClick event is functioning as ...

Connect a series of numerical input fields in Vue.js

One of the tasks I'm working on involves managing a table filled with rows of information. Users can choose multiple rows by checking checkboxes in each row, and I need to keep track of how many rows are selected by updating the totalSelected value. ...

Obtain the content slot in Vue.js 2 and convert it into a string

Is it possible to retrieve the string inside a slot before that slot is compiled? For example: <div> <slot> <component-test text="test1"></component-test> </slot> </div> I am looking for the result "<co ...

What is the best way to create a list using only distinct elements from an array?

If I have a collection of different colors: Red Blue Blue Green I aim to extract only the unique colors and store them in an array. Subsequently, I plan to incorporate each color from that array into an existing color list. The desired outcome would l ...

What steps can be taken to resolve the error ERROR TypeError: undefined is not an object when evaluating 'userData.username'?

.I need help fixing this error ERROR TypeError: undefined is not an object (evaluating 'userData.username') Currently, I am working on a small application where users are required to allow permission for their location in order to save their cit ...