详解Vue一个案例引发「内容分发slot」的最全总结

2020-06-12 21:17:17易采站长站整理

<div class="dialog-footer">
<el-button type="primary" plain>取消</el-button>
<el-button type="primary">确定</el-button>
</div>
</div>

在父组件中使用它


<dialog-panel>
<div class="dialog-header">
<h3 class="title">传递进来的标题</h3>
<button class="close">x</button>
</div>
</dialog-panel>

你会发现组件渲染之后,

<slot>
元素会被替换成组件中包裹的元素,标题的内容完全由外部传递进来。

上面我们只是嵌套了一个简单的 div 标签元素,插槽可以传入任何的元素,不管是HTML,还是组件元素。

插槽的默认内容

不仅如此,插槽还支持默认内容,当我们在外部没有传递给插槽内容时,我们可以给插槽一个默认的显示内容,如果外部有内容,默认的内容将会被外部的内容替换掉。


<div class="dialog-panel">
<slot>
<div class="dialog-header">
<h3 class="title">这是默认标题</h3>
<button class="close">x</button>
</div>
</slot>
<div class="dialog-content">这是一个标准的 dialog 对话框</div>
<div class="dialog-footer">
<el-button type="primary" plain>取消</el-button>
<el-button type="primary">确定</el-button>
</div>
</div>

在父组件中使用它,不嵌套任何的内容时,我们的组件就会有个默认的渲染标题。


<dialog-panel>
//无内容
</dialog-panel>

如果我们在父组件中提供了内容,默认的内容就会被替换。


<dialog-panel>
<div class="dialog-header">
<h3 class="title">我是新传递的标题</h3>
<button class="close">x</button>
</div>
</dialog-panel>

具名插槽

有些时候,我们除了标题有这么高的自由度之外,我们也想其它的内容也有这样的灵活性,让使用者也能通过父组件传递进来,Vue 中给我们提供了方法,我们一次可以使用很多插槽,然后给每一个插槽起个名字,也就是给我们的

<slot>
添加一个 name 属性。

于是我们就开始修改我们的对话框