Reputation: 187529
I have two Vue components, EventTask
and EventCard
. EventTask
has a currentEvent
object in data
, which I pass as a prop to EventCard
like so
<event-card :current-event="currentEvent" />
In EventCard, I initialise an event
data property from the currentEvent
prop, as suggested in this answer
export default {
name: 'EventCard',
props: {
currentEvent: {
type: Object,
required: false
}
},
data: function () {
return {
event: { ...this.currentEvent }
}
}
}
However, for some reason, the event
data property is not being set correctly. Here's what I see in the Vue developer tools
Notice that the currentEvent
prop is an object with a with a bunch of properties, but the event
data property is an empty object. Why is the data property not being initialised correctly from the prop?
Upvotes: 1
Views: 115
Reputation: 138276
This can occur if currentEvent
is updated after EventCard
has already initialized. Note that data()
is not invoked reactively, so changes to currentEvent
would not re-initialize event
.
One solution is to use a watcher on currentEvent
to copy it to event
:
export default {
watch: {
currentEvent(newValue) {
this.event = { ...newValue }
}
}
}
Upvotes: 2
Reputation: 1238
Try doing it like this instead:
export default {
name: 'EventCard',
props: {
currentEvent: {
type: Object,
required: false
}
},
data: function () {
return {
event: this.currentEvent
}
}
}
Source : https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow
Upvotes: 0
Reputation: 1878
you can try the below code
export default {
name: 'EventCard',
props: {
currentEvent: {
type: Object,
required: false
}
},
data: function () {
return {
event: null
}
},
mounted () {
this.event = this.currentEvent // you can also try clone here.
}
}
Upvotes: 0