slot詳細介紹網址:https://cn.vuejs.org/v2/api/#slot
有時候我們需要在自定義組件內書寫一些內容,例如: <com-a> <h1>title</h1> </com-a> 如果想獲取上面代碼片段中h1標簽的內容該怎么辦呢?
Vue提供了一個極為方便的內置組件<slot>;
初始界面:

初始demo:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> 使用slot分發內容</title>
</head>
<body>
<div>
<my-component-a></my-component-a>
</div>
</body>
<template id="template-a">
<div>
<h1>my-component-a</h1>
<hr />
</div>
</template>
<script type="text/javascript" src="../js/vue.js" ></script>
<script>
let comA = {
template : "#template-a"
}
new Vue({
data:{
},
components : {
"my-component-a" : comA
}
}).$mount('div');
</script>
</html>
slot放在那里,獲取到的內容就放在那里:

可以根據其name屬性進行排其位置:

定義屬性name的demo
<div>
<my-component-a>
<h1 slot='title'>大標題</h1>
<ol slot='olli'>
<li>a</li>
<li>b</li>
<li>c</li>
</ol>
<a href="#" slot='res'>點我</a>
</my-component-a>
</div>
</body>
<template id="template-a">
<div>
<slot name='title'></slot>
<h1>my-component-a</h1>
<slot name='olli'></slot>
<slot name='res'></slot>
<hr />
</div>
</template>
使用slot分發內容總的demo:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title> 使用slot分發內容</title> 6 </head> 7 <body> 8 <div> 9 10 11 <my-component-a> 12 13 <h1 slot='title'>大標題</h1> 14 <ol slot='olli'> 15 <li>a</li> 16 <li>b</li> 17 <li>c</li> 18 19 </ol> 20 <a href="#" slot='res'>點我</a> 21 </my-component-a> 22 </div> 23 </body> 24 <template id="template-a"> 25 <div> 26 <slot name='title'></slot> 27 <h1>my-component-a</h1> 28 <slot name='olli'></slot> 29 <slot name='res'></slot> 30 31 32 33 <hr /> 34 </div> 35 </template> 36 37 38 <script type="text/javascript" src="../js/vue.js" ></script> 39 <script> 40 let comA = { 41 template : "#template-a" 42 43 44 45 } 46 47 new Vue({ 48 data:{ 49 50 }, 51 components : { 52 "my-component-a" : comA 53 54 } 55 56 57 }).$mount('div'); 58 </script> 59 </html>
