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

标签 javascript vue.js vuejs2

大家好。想象一下,我们有一个父组件和一个子组件,即 PracticePersonLists (父组件)-> BCardHeaderWithButton (子组件)。现在,子级由 vue-multiselect 组成,如下所示,其中 leftAction 是一个 Object prop

<!-- 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 Hook 中生成

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

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

有人知道如何解决这个问题吗?谢谢

最佳答案

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

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

您无法设置option:this.eventsFiltersthis的使用在这里根本无效。

你应该这样做

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

并在created Hook 中设置值

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

关于javascript - 如何确保父组件将填充的 props 传递给 VueJS 中的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60112817/

相关文章:

javascript - 从underscorejs中的循环数组中删除项目

Javascript 文件 "FASW transitions"复制了我的标题信息。怎么修

javascript - 使用 Vuejs 中的 Api 响应映射 Json 文件

flask - Jinja2 和 Vuejs 绑定(bind) href 属性

javascript - 获取基于属性名称的 Vue 数据模型属性的值?

javascript - 如何使用javascript获取h1标签的高度?

javascript - 什么是描述符?

javascript - Vue FullCalendar,设置点击事件

javascript - 如何返回带有参数的属性值?

javascript - 在 vue 中从纯 HTML 执行脚本