vue之slot,组件标签嵌套

时间:2023-03-09 01:32:28
vue之slot,组件标签嵌套

vue之slot,组件标签嵌套

插槽(Slot),在各种vue的ui插件中,经常见到的多个组件标签相互嵌套(如下)就是以此为基础的。

 <el-col >
<el-checkbox >
</el-col>

而我们也经常会用到这种场景,例如封装一个边框样式的组件,组件中的内容,可以通过这种方式制作,或者将子组件提取到父组件中进行操作等等。

slot分为两种情况,匿名和具名。

1.匿名

例子:

子组件:

<div>
<h2>我是子组件的标题</h2>
<slot></slot> /*这里插入父组件在引用子组件内部的内容*/
</div>

父组件:

<div>
<h1>我是父组件的标题</h1>
<my-component>
<p>这是一些初始内容</p>
<p>这是更多的初始内容</p>
</my-component>
</div>

父组件p标签的位置也可以放一些其他组件。my-component标签中的内容,会插入到该组件slot标签的位置。

当渲染后,就会变成:

<div>
<h1>我是父组件的标题</h1>
<div>
<h2>我是子组件的标题</h2>
<p>这是一些初始内容</p>
<p>这是更多的初始内容</p>
</div>
</div>

2.具名:

具名slot其实就是对匿名slot的补充,它可以做到将组件插入到子组件的指定位置。

例子:

子组件:

<div>
<slot name="header"></slot>
<slot name="footer"></slot>
<slot></slot>
</div>

父组件:

<my-component>
<p>Lack of anonymous slot, this paragraph will not shown.</p>
<p slot="footer">Here comes the footer content</p>
<p slot="header">Here comes the header content</p>
</my-component>

渲染结果:

<div>
<p>Here comes the header content</p>
<p>Here comes the footer content</p>
<p>Lack of anonymous slot, this paragraph will not shown.</p>
</div>

参考自:https://blog.csdn.net/u014628388/article/details/76100400