在介绍slot之前,先需要搞清楚一个概念,比如
<div id=‘app’> <my-component v-show="show"></component> </div>
这个v-show的是作用于哪里的呢? 在vue中,所有在当前组件中使用的指令都是只作用于当前组件的作用域,因此,v-show虽然是在my-component中用了,但是他是在app的作用域之内,所以他是属于app的。
slot分为单个slot和具名slot。
单个slot:他主要是在我们定义组件的时候,如果在模板中插入了slot,他则被嵌入到了模板之中,当使用改组件却没有在父组件中填写任何东西时,slot中的内容将会自动填充当父组件中的组件名之中。
<div id="app" v-cloak> <child-component>我替代了slot中的内容</child-component> <child-component></child-component> /div> <script> Vue.component('child-component', { template: '<div><slot><p>如果没有插入内容,我将作为默认出现<p><slot></div>' }) var app = new Vue({ el: '#app', data: { } }); </script>
因为我在slot中插入了内容,因此,他默认就是child-component的显示内容。
如下图:
具名slot:
给slot元素命名一个name之后,就可以分发多个内容,另外,具名slot可以与刚才讲的单个slot共存哦~~~
<div id="app" v-cloak> <child-component> <h2 slot="header">标题</h2> <p>内容</p> <p>内容</p> <div slot="footer">底部信息</div> </child-component> </div> <script> Vue.component('child-component', { template: ` <div class="container"> <div class="header"> <slot name="header"><slot> </div> <div class="main"> <slot>213</slot> </div> <div class="footer"> <slot name="footer"></slot> </div> </div> ` }) var app = new Vue({ el: '#app' });
在这里,我添加了两个具名slot,分别为
header和footer,在div给slot命名,这样,具名slot会分发到同样name的div中,同时,main中的则是单个slot,所以,app中的两个p会自动分配到单个slot中。