vue中slot组件的使用

原文链接: https://www.mk2048.com/blog/blog.php?id=h0ka2ci2jjib&title=vue%E4%B8%ADslot%E7%BB%84%E4%BB%B6%E7%9A%84%E4%BD%BF%E7%94%A8

插槽(Slot)是Vue提出来的一个概念,正如名字一样,插槽用于决定将所携带的内容,插入到指定的某个位置,从而使模板分块,具有模块化的特质和更大的重用性。

Slot 是在组件模板中设置的用于在父组件中插入其孙子组件(即自身的子组件)或DOM片段的插槽。

匿名solt

子组件中

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

父组件中

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

最后结果

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

当我们要在一个组件中引入另外一个组件时,子组件就可以使用slot,父组件则引入子组件的组件名即可。

具名slot

具名Slot就是会为模板中不同部分指定相应的插入位置。但是当部分内容没有找到对应的插入位置,就会依次插入匿名的slot中,

当没有找到匿名slot时,这段内容就会被抛弃掉。

子组件中

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

父组件中

<slider>
    <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>
</slider>

最后结果

<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>

这是slot的基本用法,其他用法可参考:

https://www.w3cplus.com/vue/vue-slot.html


更多专业前端知识,请上 【猿2048】www.mk2048.com

猜你喜欢

转载自blog.csdn.net/qq_45670012/article/details/102769621