如何确保父组件将填充的 props 传递给 VueJS 中的子组件



大家好。假设我们有一个父组件和一个子组件,即PracticePersonLists(父(->BCardHeaderWithButton(子(。现在孩子由一个vue-multiselect组成,就像这样leftAction是对象道具

<!-- Multiselect -->
<multiselect
v-if="leftAction.type === 'options'"
v-model="leftAction.model"
:options="leftAction.options"
:placeholder="leftAction.placeholder"
:searchable="true"
:show-labels="true"
:allow-empty="false"
/>

父级按如下方式呈现子项:

<b-card-header-with-button
v-if="(isHR && (person.md_current === 1))"
card-title="Events"
:left-action="eventsLeftAction"
:right-action="eventsRightAction"
@rightActionClick="addEvent()"
/>

eventsLeftAction是父级内部的数据属性,如下所示:

eventsLeftAction: {
show: true,
type: 'options',
options: this.eventsFilters,
model: this.compEventsLeftActionModel,
placeholder: 'Select Event'
}

eventsFilters在父级的created钩中生成

this.eventsFilters = await buildNonBackEndFilterOptions(this.events, 'eventHead', 'eventGroup')

但问题是在页面加载时,子组件找不到其leftAction.options因此它返回为未定义。我们认为这与子组件在父组件之前呈现的事实有关,因此它正在寻找尚不存在的数据......通常我们通过设置布尔值dataLoaded来克服这个问题,并且仅在布尔值为真时才渲染子项,但在这种情况下似乎不起作用

有人知道如何克服这个问题吗?谢谢

这不是真的。 父级created子级渲染之前调用。 代码中的问题是

eventsLeftAction: {
show: true,
type: 'options',
options: this.eventsFilters,
model: this.compEventsLeftActionModel,
placeholder: 'Select Event'
}

您无法设置option:this.eventsFilters在此处使用this根本无效。

你应该这样做

eventsLeftAction: {
show: true,
type: 'options',
options: null,
model: null,
placeholder: 'Select Event'
}

并在created钩子中设置值

async created(){
//you can here whatever you want. its called before child rendered
this.eventsLeftAction.options= await buildNonBackEndFilterOptions(this.events, 
'eventHead', 'eventGroup')
}

我们现在能想到的唯一解决方案是从父级的created钩子将选项存储在 Vuex 中,然后在子级中用mapState拉动它们。

父母:

this.eventsFilters = await buildNonBackEndFilterOptions(this.events, 'eventHead', 'eventGroup')
this.setPracticePersonListsEventsFilters(this.eventsFilters)
methods: {
...mapMutations('practice', ['setPracticePersonListsEventsFilters']),
}

孩子:

<multiselect
v-if="leftAction.type === 'options'"
v-model="leftAction.model"
:options="compOptions"
:placeholder="leftAction.placeholder"
:searchable="true"
:show-labels="true"
:allow-empty="false"
/>
computed: {
...mapState('practice', ['practicePersonListsEventsOptions']),
compOptions () {
switch (this.$route.name) {
case 'app.practice.person.lists':
return this.practicePersonListsEventsOptions
default:
return ''
}
}
}

如果有人知道更好的解决方案,如果您分享,我们将不胜感激。

最新更新