2017-07-14 48 views
3

我想構建一個表組件。VueJs:將動態組件作爲道具傳遞給另一個組件並呈現它們

我想定義並傳遞網格的列元數據作爲數組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 
    }] 
] 

將竭誠爲闡述/澄清一下,如果問上面是不明確的。

+0

https://vuejs.org/v2/guide/components.html#Dynamic-Components – thanksd

+0

@thanksd謝謝你,但是在我的情況,我不會有什麼成分會傳遞到parent-comp,以便讓組件在「components」屬性中列出 – Chandu

+0

如果您傳遞組件定義,則不需要。 – Bert

回答

5

正如上面評論中所建議的那樣,您可以在模板中使用動態組件,並在屬性中傳遞組件的定義。

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/[email protected]/dist/vue.js"></script> 
 
<div id="app"> 
 
    <parent-comp :columns="columns"></parent-comp> 
 
</div>

+2

如果他需要傳遞道具,他可以這樣做:https://jsfiddle.net/ro1j8xmv/ – thanksd

相關問題