Setting a default date dynamically for v-date-picker in the parent component, and then retrieving the updated date from the child component

I'm working with a custom component that utilizes the v-date-picker in various instances. My goal is to have the ability to dynamically set the initial date from the parent component, while also allowing the date to be modified from the child component.

Below is the code snippet from the parent component:

<template>
  <DatePickerMenu @selectedDate="selectedExpirationDate" :selectedDate="this.date"></DatePickerMenu>
</template>

<script>
data() {
    return {
      date: '2021-04-29', //initial date for testing, will eventually be calculated within this parent component
    }
},
methods: {
selectedExpirationDate(value) {
      this.expiration_date = value;
    },
},
</script>

In the child component:

<template>
  <v-menu
    ref="datePickerMenu"
    v-model="datePickerMenu"
    :close-on-content-click="false"
    :return-value.sync="selectedDate"
    transition="scale-transition"
    offset-y
    min-width="auto"
  >
    <template v-slot:activator="{ on, attrs }">
      <v-text-field
        class="form"
        v-model="selectedDate"
        label="Expiration date *"
        hint="Minimum expiration date: one week from today"
        prepend-icon="mdi-calendar"
        readonly
        v-bind="attrs"
        v-on="on"
        :rules="requiredRules"
      ></v-text-field>
    </template>
    <v-date-picker
      v-model="selectedDate"
      no-title
      scrollable
      color="primary"
    >
      <v-spacer></v-spacer>
      <v-btn
        text
        color="primary"
        @click="datePickerMenu = false"
      >
        Cancel
      </v-btn>
      <v-btn
        text
        color="primary"
        @click="$refs.datePickerMenu.save(selectedDate)"
      >
        OK
      </v-btn>
    </v-date-picker>
  </v-menu>
</template>

<script>
export default {
  name: "DatePickerMenu",
  data () {
    return {
      datePickerMenu: false,
      //selectedDate: this.setSelectedDate, and changing the 'selectedDate' props to setSelectedDate
    }
  },
  props: ['selectedDate'],
  watch: {
    selectedDate: function() {
      this.$emit('selectedDate', this.selectedDate);
    },
  },
}

After implementing this setup, I noticed that although the date picker initially displays the correct date passed from the parent component, any changes made to the selected date triggers the following warning message:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "selectedDate"

I attempted to resolve this issue by setting a local data using the passed props

//selectedDate: this.setSelectedDate,
, but encountered a scenario where the default selected date works only once, failing to update when changed in the parent component.

I hope my problem is clear... Any suggestions for a solution?

Thank you in advance.

Answer №1

If you want to synchronize data between parent and child components in Vue.js, you can utilize the .sync modifier as shown below:

In your parent component:

<DatePickerMenu
    :selectedDate.sync="this.date"
    @selectedDate="selectedExpirationDate" 
/>

And in your child component, you can create a computed property like this:

<v-date-picker
    v-model="selectedDateComputed"
    no-title
    scrollable
    color="primary"
>
computed: {
  selectedDateComputed: {
     get(): {
        return this.selectedDate;
     }
     set(newDate): {
        this.$emit('update:selectedDate', newDate);
     }
  }
}

Remember to apply the same approach for v-text-field as well.

For more details on using the sync modifier in Vue.js, refer to the vue sync modifier documentation.

Answer №2

It's running smoothly, thank you!

Just an FYI, while the approach was spot-on, there were a few syntax errors:

computed: {
    selectedDateComputed: {
     get: function () {
        return this.selectedDate;
     },
     set: function(newDate) {
        this.$emit('update:selectedDate', newDate);
     }  
  },

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

Having trouble converting a timestamp to a date in JavaScript

My database uses MongoDB and has a timestamp field with unique formats, such as: 1657479170.7300725 1657479170.7301126 1657479170.7301197 1657479170.9120467 1657479170.932398 Converting these timestamps to the date format YYYY-MM-DD yields the correct res ...

Explore various THREE.JS 3D models through a clickable link

I am struggling to make each object open a new page using a URL when clicked. No matter what I try, it doesn't seem to work properly. Can someone point out what I might be missing or doing wrong? Here is the click event code for the objects. If needed ...

Unable to get the div to properly follow when scrolling, even when using the fixed position attribute

My webpage is divided into two sections - left and right. I've used divs to create the left navigation and right content. However, when scrolling down the page, only the right portion scrolls while the left navigation remains fixed. I'm looking ...

Typescript implementation for a website featuring a single overarching file alongside separate files for each individual webpage

Although I've never ventured into the realm of Typescript before, I am intrigued by its concept of "stricter JS". My knowledge on the subject is currently very limited as I am just starting to experiment with it. Essentially, I have developed my own ...

What is the best way to incorporate a countdown timer on an ASP.NET webpage?

Looking to display a countdown timer in the top right corner of my ASP page that starts from 00:00:30 and counts down to 00:00:00 before resetting back to 00:00:30. Does anyone have any suggestions on how to achieve this? ...

What is the best way to adjust the content of a Bootstrap Column to be at the bottom of the column

Currently diving into the world of Bootstrap for my personal website, I'm encountering a challenge in aligning the content of my sidebar to the bottom. My quest for a solution led me through numerous threads without success. <!-- wordsmith: < ...

Adjust the position of the footer up or down based on changes in page content height

If I have jQuery at my disposal, how can I achieve the following task? There is a div on the page with dynamic content and no fixed height. The height of this div changes as users type and content appears or disappears accordingly. Although everything is ...

What is the correct method for downloading an Excel file in a Vue.js application?

I am having difficulty downloading an Excel file in xlsx format using my Vue.js application. The Vue.js application sends a post request to the Node.js application which then downloads the Excel file from a remote SFTP server. The backend application is fu ...

What could be causing my second ajax call to render the page unresponsive?

I am encountering an issue with my AJAX call. It works fine on the first attempt, but when I try to call it a second time, the page becomes unresponsive. I am not sure what is causing this issue. The code is located within the document ready function. The ...

Displaying various Ajax html responses

The function $('.my-button').click(function(e) is designed to display the output of the MySQL query in display.php, presented in HTML format. While it functions correctly, since each button is looped for every post, the script only works for the ...

What is the best way to append data to the end of an object using ReactJS Hooks?

Looking to set up a checkbox page in ReactJS where data is filtered by checkboxes from different categories using ReactJS hooks. Currently, I am storing the selected checkboxes as an object: { color: 'orange', shape: 'square' } ...

Make sure to declare rest parameters first when using Typescript

I am dealing with a function that takes in multiple string arguments and one final argument of a complex type, which is called Expression. This particular code looks like this in JavaScript: function layerProp(...args) { const fields = args.slice(0, -1) ...

Working with npm objects across multiple files

My goal is to integrate the npm package for parallax (lax.js) into my project. The documentation states that in order to initialize it, the following code snippet should be included: window.onload = function () { lax.init() // Add a driver that we use ...

Alter the background color of the text input when it is selected for exit

How can I adjust the input field color when text is selected? I'm looking to get rid of the dark grey box highlighting. (Check out the image below) https://i.sstatic.net/OgWaz.gif <div id="ember1102" class="ember-view"> <i class="fa fa ...

The tag's onclick function that was dynamically created was not triggering in jQuery

I created a web application using jquery mobile and ran into an issue. I am trying to call a function by clicking on a dynamically generated anchor tag, but it's not working and showing an error that the function is not defined. Any assistance on this ...

Unable to capture HTML form input in $_POST[]

I've encountered an unusual issue while transferring data from an email form (HTML5) to ajax/JSON and receiving false in order to prevent redirection to the php script after pressing the submit button. When I include commas between each data paramete ...

Is there a way to send the image object to the onclick function as it is being assigned?

I apologize if my question is a bit unclear, as I am currently teaching myself how to use javascript. I am working on generating image thumbnails dynamically and would like the ability for users to enlarge the image when they click on the thumbnails. The p ...

Attempting to use Model.remove() is proving to be completely ineffective

Currently, I am utilizing expressjs (version 3.10.10), mongoose (version 3.10.10), and mLab for my project. Below is the code snippet: app.get("/deleteDevice/:query", function(req, res) { var query = req.params.query; query = JSON.stringify(quer ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

Tips for showing an alert when incorrect login credentials are entered on a login form

<?php include('includes/config.php'); if(isset($_POST["submit"])){ $empid=$_POST["empid"]; $pass=$_POST["password"]; $query=mysqli_query($conn,"SELECT employee_id, fname,lname,empid,password, status, role FROM employee where empid='$emp ...