[英]Initialising data from an object prop in a Vue component
I have two Vue components, EventTask
and EventCard
.我有两个 Vue 组件, EventTask
和EventCard
。 EventTask
has a currentEvent
object in data
, which I pass as a prop to EventCard
like so EventTask
在data
中有一个currentEvent
object ,我像这样将它作为道具传递给EventCard
<event-card :current-event="currentEvent" />
In EventCard, I initialise an event
data property from the currentEvent
prop, as suggested in this answer在 EventCard 中,我从currentEvent
道具初始化一个event
数据属性,如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.但是,由于某种原因,未正确设置event
数据属性。 Here's what I see in the Vue developer tools这是我在 Vue 开发者工具中看到的
Notice that the currentEvent
prop is an object with a with a bunch of properties, but the event
data property is an empty object.请注意, currentEvent
属性是一个 object,带有一堆属性,但event
数据属性是一个空的 object。 Why is the data property not being initialised correctly from the prop?为什么没有从道具正确初始化数据属性?
This can occur if currentEvent
is updated after EventCard
has already initialized.如果在EventCard
已经初始化之后更新currentEvent
,就会发生这种情况。 Note that data()
is not invoked reactively, so changes to currentEvent
would not re-initialize event
.请注意, data()
不会被动调用,因此对currentEvent
的更改不会重新初始化event
。
One solution is to use a watcher on currentEvent
to copy it to event
:一种解决方案是在currentEvent
上使用观察者将其复制到event
:
export default {
watch: {
currentEvent(newValue) {
this.event = { ...newValue }
}
}
}
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.
}
}
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来源: https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.