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.