为了让组件可以组合,需要一种方式来 混合父组件的内容与子组件自己的模板。—> 内容分发
Vue 实现了一个内容分发 API,用特殊的 slot
元素作为原始内容的插槽。
编译的作用域
在深入内容分发 API 之前,需要先明确各个内容在哪个作用域内编译
<div id="app">
<child-component v-show="childshow"></child-component>
</div> // 父组件的作用域
<script>
var app = new Vue({
el: '#app',
data: {
message: '父组件的信息',
childshow: true
},
components: {
'child-component': {
template: '<div>{
{message}}</div>', // 子组件的作用域
data: function() {
return {
message: '子组件的信息',
childShow: false
}
}
}
}
})
</script>
上面的代码中 childshow 应该绑定到的是父组件的数据,而显示的是子组件中的信息,所以 message 绑定到的是子组件的数据。
组件的作用域简单的来说就是:父组件模板的内容在父组件作用域内编译,子组件模板的内容在子组件作用域内编译。
插槽用法
父组件的内容和子组件混合以弥补视图的不足。
- 单个插槽
<div id="app">
// 父组件插入了内容,显示父组件的内容
<my-component>
<p>我是父组件的内容</p> // 插槽
</my-component>
<my-component>
// 父组件没有插入内容则显示子组件 slot 标签里的内容
</my-component>
</div>
<script>
Vue.component('my-component', {
template: `<div>\