正式介紹slot前, 需要先知道一個(gè)感念: 編譯的作用域.比如父組件中有如下模板:
<child-component>
{{ message }}
</child-component>
這里的 message 就是一個(gè) slot, 但是它綁定的是父組件的數(shù)據(jù),而不是組件 <child-component> 的數(shù)據(jù).
父組件模板的內(nèi)容在父組件作用域內(nèi)編譯,子組件模板的內(nèi)容是在子組件作用域內(nèi)編譯.例如下面的代碼示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>示例</title>
</head>
<body>
<div id="app">
<child-component v-show="showChild"></child-component>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
Vue.component('child-component', {
template: '<div>子組件</div>'
});
var app = new Vue({
el: '#app',
data: {
showChild: true
}
})
</script>
</body>
</html>
這里的狀態(tài) showChild 綁定的是父組件的數(shù)據(jù),如果想在子組件上綁定,那應(yīng)該是:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>示例</title>
</head>
<body>
<div id="app">
<child-component></child-component>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
Vue.component('child-component', {
template: '<div v-show="showChild">子組件</div>',
data: function () {
return {
showChild: true
}
}
});
var app = new Vue({
el: '#app'
})
</script>
</body>
</html>
因此, slot 分發(fā)的內(nèi)容,作用域是在父組件上的.