Developing a calendar with limited availability for selecting future dates and restricting the ability to choose past dates

I am currently working on creating a calendar in Vue.js that allows users to select dates only from the current day up to the next 30 days. Dates prior to the current date are disabled, as well as dates beyond the initial 30-day period.

While I have experience implementing similar functionality in JavaScript, you can view an example here: https://codepen.io/tarik-bisevac/pen/WNemOXO

However, I am facing challenges when trying to port this code to Vue.js

Below is my attempt at using Vue:


let app = new Vue({
    el: '#app',
    data:{
        min: dtToday,
        max: maxDate
    },
    computed: {
        dtToday(){
            new Date().toISOString().slice(0,10)
firstDate.setAttribute('min',dtToday)
firstDate.setAttribute('max',dtToday)
        },
        maxDate(){
            let month = new Date().getMonth()+2
let day = new Date().getDate()
let year = new Date().getFullYear()

new Date(`${month}/${day}/${year}`).toISOString().slice(0,10)
        }
    }
})

HTML:

    <div id="app">
        <input type='date' v-model='min'> 
        <input type='date' v-model='max'> 
    </div>

An error message "Uncaught ReferenceError: Cannot access 'dtToday' before initialization" is being displayed.

I have attempted different strategies using methods and computed properties, but I am still unsure of the correct approach.

Answer №1

You are unable to call computed from data since data is required during component creation, and computed is not accessible before creation.

Therefore, you can leave the min max values blank in data and calculate them after creation using the created() or mounted() life cycle hook.

Here's an example:

let app = new Vue({
    el: '#app',
    data:{
        min:'',
        max:'',      
    },
    created(){
      this.computeMinMaxDate();
    },
    methods:{
      computeMinMaxDate(){
        let todayDate = new Date().toISOString().slice(0,10);
        this.min =todayDate;
        let month = new Date().getMonth()+2
        let day = new Date().getDate()
        let year = new Date().getFullYear()
        // create html input format
        let maxDate = new Date(`${month}/${day}/${year}`).toISOString().slice(0,10);
        this.max= maxDate;
      }
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<div id="app">
     <input type='date' :min="min" :max="min"> 
     <input type='date' :min="min" :max="max"> 
</div>

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

dotdotdot.js is only functional once the window has been resized

For my website, I am attempting to add an ellipsis to multiline paragraphs that exceed a certain height. I have incorporated the dotdotdot jquery plugin from here. An odd issue arises when the page is refreshed, as the ellipsis does not appear until I res ...

Insert the GET object into an empty object within the data and then send it back

Here is the Vue application I am working with: new Vue({ name: 'o365-edit-modal-wrapper', el: '#o365-modal-edit-wrapper', data: function() { return { list: {}, } }, created() { thi ...

A guide to resolving cross-origin resource sharing issues using a reverse proxy

After creating a JavaScript web application for processing documents, I am now looking to integrate with web services like NLTK-server, TIKA-server, and SOLR for further analysis. While I can successfully access the REST endpoints of these services using c ...

Shorten a string once a particular word is found in either Smarty or JavaScript/jQuery

I'm currently working on a website and encountering a minor bug related to the addition of content at the end of some strings. For instance: style="background-image:url({$sub.image});" displays style="background-image:url(http://blablalba.fr/phoenix ...

Encountering a React JS error with Admin on Rest while making an API request

When making an API call (GET) with React.js using Admin on Rest, I encountered an issue. The server returns data when calling localhost:5001/cities, but there seems to be an error on the client side as indicated by the browser log: failure.js:18 Error: Th ...

Is there a way to develop a login form that retrieves information from a Google Sheet database?

Please help me with a solution. I have developed a registration form which effectively saves users' information in a Google Sheet. However, now I am yearning to create a login form that verifies the stored data and redirects the user to a different pa ...

The installation of "npm" was completed successfully, however there seems to be an issue when

I am currently facing an issue while trying to set up http-server, bower, and grunt on my Windows machine. After successfully installing them using npm install, I encountered a 'command not found' error when attempting to run the commands. Even a ...

Utilizing Highcharts-vue for Interactive Stacked Column Charts with Drilldown Feature

I'm currently attempting to recreate a chart similar to the one shown in this example using Vue.js. Admittedly, I am in the process of learning Vue.js, so I find it beneficial to replicate existing projects as a way to build confidence quickly. One ...

Service Worker Tips: Caching the initial page with dynamic content

I have a single-page application with a dynamic URL generated using a token, for example: example.com/XV252GTH, which includes various assets such as CSS and favicon. This is how I implement the Service Worker registration: navigator.serviceWorker.regist ...

Interested in integrating Mockjax with QUnit for testing?

I recently came across this example in the Mockjax documentation: $.mockjax({ url: "/rest", data: function ( json ) { assert.deepEqual( JSON.parse(json), expected ); // QUnit example. return true; } }); However, I'm a bit confused abou ...

Creative ways to use images as borders with CSS in React JS

import React, { Component } from 'react'; class BigText extends Component { constructor(props) { super(props); this.state = { title: '', text: '', summary: '' ...

Using the select method in JavaScript arrays

Are the functionalities of JavaScript and Ruby similar? array.select {|x| x > 3} Could it be done like this instead: array.select(function(x) { if (x > 3) return true}) ...

I am unable to align the image in the center, what could be causing it not to center properly?

Why does my code center in mobile view but not in Desktop? How can I solve this issue? I have tried using display: block; margin: auto; width:100%; and text-align: center;, but it did not work. let $slides, interval, $selectors, $btns, currentIndex, ne ...

Is it possible to leverage a reusable asynchronous call (using Axios GET) in the mounted hook of Nuxt

Is it possible to reuse the asyncData request or data when rendering a page with Nuxt, Vue, and Axios? For example, after rendering a response, can the same data be used for subsequent actions such as filtering or sorting on the page, or would a new call ...

Link a template to a formly field when clicking on another field within an Angular formly form

Recently, I have been utilizing a Formly form that includes a section for displaying dynamic HTML content. Within this form, I am using the template field to initialize some HTML content when the page loads. However, I have encountered an issue where chang ...

One can pass parameters to a promise's success callback within AngularJS using $q

I have encountered a situation that is similar to the one described in this post, but I am still unsure about how to implement it. I could use some assistance with setting up a successful callback. This is the current functioning code: function getStuff( ...

retrieval: unspecified information obtained through body parsing (Node.js Express)

Having just started working with React.js and Node.js, I encountered a simple issue that I can't seem to solve. I am using the lightweight fetch API to post data and trying to receive that data using body-parser, but it always returns undefined. impo ...

Failure to receive Ajax XML data in success callback

I am struggling to access the book.xml file that is located in the same folder as other files. Everything seems fine, but the ajax function refuses to enter the success state and instead shows an [object object] error message. The XML file is very simple, ...

Angular JS is encountering an issue where the promise object is failing to render correctly

I'm currently learning Angular and I have a question about fetching custom errors from a promise object in Angular JS. I can't seem to display the custom error message on my HTML page. What am I missing? Below is my HTML file - <!DOCTYPE htm ...

Can Ajax be utilized to invoke an internal function within a web application?

Brand new to PHP, this is a whole new world for me. Currently, I am attempting to dynamically update a drop down list from 1-10 based on the selection of a previous drop down list. The initial drop down list allows you to choose tables numbered 1-35, whil ...