什麼是插槽?
插槽就是子元件中的提供給父元件使用的一個占位符,用<slot></slot> 表示,父元件可以在這個占位符中填充任何模闆代碼,如 HTML、元件等,填充的内容會替換子元件的<slot></slot>标簽。舉個例子:
1、先看一下下面的代碼,聲明一個child-component元件,如果現在我想在<child-component></child-component>内放置一些内容,結果會是怎樣?
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>插槽</title>
<script src="../vue.min.js"></script>
</head>
<body>
<div id="app">
<div>使用slot分發内容</div>
<div>
<child-component>
<div>多雲,最高氣溫34度,最低氣溫28度,微風</div>
</child-component>
</div>
</div>
<script>
Vue.component('child-component', {
template: '<div>' +
'<h1>今天天氣狀況:</h1>' +
'</div>'
});
var app = new Vue({
el: '#app'
});
</script>
</body>
</html>
顯示效果:輸出内容還是在元件中的内容,在 <child-component>内寫的内容沒起作用。
2、我們現在給元件增加一個<slot></slot>插槽,則就起作用了
<script>
Vue.component('child-component', {
template: '<div>' +
'<h1>今天天氣狀況:</h1>' +
'<slot></slot>' +
'</div>'
});
var app = new Vue({
el: '#app'
});
</script>
參考:
https://www.cnblogs.com/mandy-dyf/p/11528505.html