【问题标题】:Vue Dynamic Component & Dynamic propsVue 动态组件和动态道具
【发布时间】:2020-10-24 01:14:50
【问题描述】:

我有一个如下所示的模态组件

<modal>
    <component
        :is="modalComponent"
    />
</modal>

而且我需要将不同的道具传递给动态组件。

组件 A 需要一个标题和名称数组 组件 B 需要标题、事件数组和日期作为字符串。

将不同的道具传递给动态组件的最佳方式是什么?我真的不想将所有道具传递给动态组件。

<modal>
    <component
        :is="modalComponent"
        :title='title'
        :names='names'
        :events='events'
        :eventDate='eventDate'
    />
</modal>

【问题讨论】:

    标签: vue.js components vue-props


    【解决方案1】:

    使用计算属性生成道具:

    <component :is="modalComponent" v-bind="props"/>
    
    computed: {
      props() {
        if (this.modalComponent === 'ComponentA') {
          return {
            title: this.title,
            names: this.names,
          }
        } else if (this.modalComponent === 'ComponentB') {
          return {
            title: this.title,
            events: this.events,
            eventDate: this.eventDate,
          }
        }
      }
    }
    

    【讨论】:

    • 您应该添加一个else 以返回一个空对象。它将处理除 A 和 B 之外的所有组件,而不是抛出错误。
    • 在这种情况下它不会抛出错误,props 将只是 undefined 并且 Vue 可以处理得很好。无论如何,OP没有提到还有其他情况,或者在这种情况下该怎么做。这是与问题无关的多余绒毛。
    • 感谢您的回复,我确实看到过这样的例子,老实说我不太喜欢它,只是看起来有点冗长。
    猜你喜欢
    • 2019-02-07
    • 2018-10-20
    • 2020-05-09
    • 2018-08-07
    • 2017-11-29
    • 2019-04-03
    • 2018-06-10
    • 2021-04-03
    • 2018-06-12
    相关资源
    最近更新 更多