VueJs:将动态组件作为道具传递给另一个组件并渲染它们

Cha*_*ndu 9 vue-component vuejs2

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

我想定义并将网格的列元数据作为数组prop传递,并将实际数据作为另一个prop传递给网格.

我能够在没有太多问题的情况下实现这一点.

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

有没有办法将动态组件作为prop传递,然后呈现此组件?

<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>
Run Code Online (Sandbox Code Playgroud)

dataSource数据可以是这样的

[
  columns: [{
    name: "something",
    customComponent: SomeCustomComponent
  }, {
    name: "another thing",
    customComponent: AnotherOtherCustomComponent
  }]
]
Run Code Online (Sandbox Code Playgroud)

如果上述问题不明确,将很乐意详细说明/澄清.

Ber*_*ert 7

如上面的注释所示,您可以在模板中使用动态组件,并在属性中传递组件的定义.

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
    }]
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <parent-comp :columns="columns"></parent-comp>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 如果他需要传递道具,他可以这样做:https://jsfiddle.net/ro1j8xmv/ (2认同)