了解插槽slot之前,我们先说一下作用域。父组件模板的所有东西都会在父级作用域内编译;子组件模板的所有东西都会在子级作用域内编译。因此slot分发的内容,作用域是在父组件上。
1、单个slot
在子组件内使用特殊的<slot>元素就可以作为这个子组件开启一个slot插槽,在父组件模板里,插入在子组件标签内的所有内容将替代子组件的<slot>标签及它的内容。
<div id="app">
<child-component">
<p>分发的内容</p>
</child-component>
</div>
<script>
Vue.component('child-component',{
template:'<div><slot>如果父组件没有插入内容,我将作为默认出现</slot></div>'
});
new Vue({
el:'#app',
data:{
}
});
</script>
子组件child-component 的模板内定义了一个<slot>元素,并且用一个<p>作为默认的内容,在父组件没有使用slot 时,会渲染这段默认的文本;如果写入了slot, 那就会替换整个<slot> 。所以上例渲染后的结果为:
<div id=”app”>
<div>
<p>分发的内容</p>
</div>
</div>
【注意】子组件<slot>的备用内容,它的作用域是子组件本身。
2、具名slot
<slot> 元素有一个特殊的特性:name。这个特性可以用来定义额外的插槽:
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
在向具名插槽提供内容的时候,我们可以在一个父组件的 <template> 元素上使用slot 特性:
<base-layout>
<template slot="header">
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template slot="footer">
<p>Here's some contact info</p>
</template>
</base-layout>