【问题标题】:VueJs: Pass Dynamic Components as props to another Component and render themVueJs:将动态组件作为道具传递给另一个组件并渲染它们
【发布时间】:2017-12-19 18:19:59
【问题描述】:

我正在尝试构建一个表格组件。

我想为网格定义列元数据并将其作为数组道具传递,并将实际数据作为另一个道具传递给网格。

我能够毫无问题地实现这一目标。

但是,现在我想传递一个动态组件作为每个列定义的一部分,以便用户可以定义/控制单元格的呈现方式(在同一单元格中带有编辑删除按钮的内容等)

有没有办法将动态组件作为道具传递,然后渲染该组件?

<parent-comp>
  <tr class="" v-for="result in dataSource">
    <template v-for="column in columns">
      <td>
        <template v-if="column.customComponent">
          ######## How do I render this customComponent ########
        </template>
      </td>
    </template>
  </tr>
</parent-comp>

dataSource 数据可能是这样的

[
  columns: [{
    name: "something",
    customComponent: SomeCustomComponent
  }, {
    name: "another thing",
    customComponent: AnotherOtherCustomComponent
  }]
]

如果上述问题不清楚,我们很乐意对此进行详细说明/澄清。

【问题讨论】:

标签: vuejs2 vue-component


【解决方案1】:

正如上面的 cmets 所建议的,您可以在模板中使用动态组件,并在您的属性中传递组件的定义。

console.clear()

const ColumnOne = {
  template: `<h1>I am ColumnOne</h1>`
}

const ColumnTwo = {
  template: `<h1>I am ColumnTwo</h1>`
}

Vue.component("parent-comp",{
  props:["columns"],
  template:`
    <div>
      <component v-for="column in columns" 
                 :is="column.customComponent" 
                 :key="column">
      </component>
    </div>
  `
})

new Vue({
  el:"#app",
  data:{
    columns:[{
      name: "something",
      customComponent: ColumnOne
    }, {
      name: "another thing",
      customComponent: ColumnTwo
    }]
  }
})
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <parent-comp :columns="columns"></parent-comp>
</div>

【讨论】:

猜你喜欢
  • 2021-07-08
  • 2022-01-06
  • 2020-04-07
  • 2021-09-08
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多