1.插槽
插槽,內置組件slot,作爲承載分發內容的出口
先看一下下面的代碼:聲明一個child-component組件,如果現在我想在
<child-component></child-component>
內放置一些內容,結果會是怎樣?
<div id="app">
<child-component></child-component>
</div>
<script>
Vue.component('child-component',{
template:`
<div>Hello,World!</div>
`
})
let vm = new Vue({
el:'#app',
data:{
}
})
</script>
<child-component>你好</child-component>
輸出內容還是在組件中的內容Hello,World!,在 <child-component>
內寫的你好沒起作用。
我們現在給組件增加一個插槽
Vue.component('child-component',{
template:`
<div>
Hello,World!
<slot></slot>
</div>
`
})
回到頁面發現我們在<child-component></child-component>
內寫的你好起作用了!!!
沒有插槽的情況下在組件標籤內些一些內容是不起任何作用的,當我在組件中聲明瞭slot元素後,在組件元素內寫的內容就會跑到它這裏了!
2.具名插槽
在組件中,我給插槽起個名字,一個名字叫"girl",一個名字叫"boy",還有一個不起名字。然後再<child-component></child-component>
內,slot屬性對應的內容都會和組件中name一一對應。而沒有名字的,就是默認插槽!
<div id="app">
<child-component>
<h1 slot="girl">漂亮、購物、逛街</h1>
<h2 slot="boy">帥氣、才實</h2>
<h3>我是一類人,我是默認的插槽</h3>
</child-component>
</div>
<script>
Vue.component('child-component',{
template:`
<div>
<h4>這個世界不僅有男人和女人</h4>
<slot name="girl"></slot>
<div style="height:1px;background-color:red;"></div>
<slot name="boy"></slot>
<div style="height:1px;background-color:red;"></div>
<slot></slot>
</div>
`
})
let vm = new Vue({
el:'#app',
data:{
}
})
</script>