vuejs2 - VueJs : Pass Dynamic Components as props to another Component and render them

标签 vuejs2 vue-component

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

我想定义并将网格的列元数据作为数组 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>

数据源数据可以是这样的
[
  columns: [{
    name: "something",
    customComponent: SomeCustomComponent
  }, {
    name: "another thing",
    customComponent: AnotherOtherCustomComponent
  }]
]

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

最佳答案

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

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>

关于vuejs2 - VueJs : Pass Dynamic Components as props to another Component and render them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45106508/

相关文章:

javascript - 尝试更新图表时我是否正确使用了chart.update()?

javascript - Vue中使用SSR时在何处调用 "Vue.use(plugin)"

javascript - 如何设置 eslint 以仅在单文件 vue 组件中将 lodash 检测为全局?

javascript - VueJS/VueX 超出最大调用堆栈大小

javascript - 删除对象属性 (VueJs)

vue.js - 在自定义组件上使用时 v-model 和 .sync 有什么区别

vue.js - Vue Router Keep-Alive 包括不工作

javascript - Vue.js 无法在方法中遍历对象

javascript - vue-good-table 行上是否有右键单击事件以显示上下文菜单?

vue.js - 从外部 javascript 访问 Vue 组件范围