2017-06-16 54 views
1

一個具體的例子。我想爲Bootstrap的網格佈局構建一個組件。我希望能夠做這樣的事情(這是無效的Vue公司代碼):如何將數據傳遞給組件中的插槽?

BGrid.vue:

<template> 
    <div class="container"> 
    <div class="row"> 
     <slot name="col" class="'col' + colNumber"></col> 
    </div> 
    </div> 
<template> 

App.vue

<template> 
    <div class="container"> 
    <b-grid> 
     <template slot="name" :colNumber="2"> 
     <p>Content for the column 1</p> 
     </template> 
    <template slot="name" :colNumber="4"> 
     <p>Content for the column 2</p> 
     </template> 
    </b-grid> 
    </div> 
<template> 

(我想能夠針對不同的插槽具有不同的colNumbers)。

有沒有辦法在Vue中完成類似的事情?

+0

爲什麼不把它作爲道具傳遞給'b-grid'組件? – Bert

+0

@BertEvans你能給我一個示例代碼?我仍然可以添加內容到插槽嗎?如何控制哪個插槽具有哪個colNumber? – alex

回答

1

如果要發射div,並將類設置爲col-加上列號,可以將列號作爲屬性傳遞給組件。

console.clear() 
 

 
Vue.component("b-grid",{ 
 
    props:["colNumber"], 
 
    template: ` 
 
    <div class="container"><slot></slot></div> 
 
    ` 
 
}) 
 

 
Vue.component("row",{ 
 
    template: ` 
 
    <div class="row"><slot></slot></div> 
 
    ` 
 
}) 
 

 
Vue.component("column",{ 
 
    props:["colNumber"], 
 
    template:` 
 
    <div :class="'col-' + colNumber"> 
 
     <slot></slot> 
 
    </div> 
 
    ` 
 
}) 
 

 
new Vue({ 
 
    el:"#app" 
 
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script> 
 
<div id="app"> 
 
    <b-grid> 
 
    <row> 
 
     <column :col-number="2"> 
 
     <p>Content for 2 column</p> 
 
     </column> 
 
     <column :col-number="6"> 
 
     <p>Content for 6 column</p> 
 
     </column> 
 
    </row> 
 
    </b-grid> 
 
</div>

在上述例子中,檢查內容看出,類適當設定。

+0

如果我想爲不同的列添加不同的colNumbers,該怎麼辦?請看我更新的問題。 – alex

+0

@alex我不會使用插槽,我可能會使用列組件。如果這是爲了複製Bootstrap的網格系統,你可能想要一個容器,行和列是正確的? – Bert

+0

@alex檢查更新。 – Bert