繁体   English   中英

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

[英]How to ensure that parent is passing populated props to a child component in VueJS

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

<!-- 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是在 parent 的created钩子中生成的

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

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

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

我们现在能想到的唯一解决方案是将选项从父级的created挂钩存储在 Vuex 中,然后在子mapState中使用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 ''
    }
  }
}

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

这不是真的。 在子渲染之前调用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')
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM