Vue 插槽分发内容

来源:互联网 发布:php gzip 优缺点 编辑:程序博客网 时间:2024/05/22 04:51

1.在Vue工程化开发中是以组件为单位的

2.组件个人理解是将常用或通用的代码片段独立起来,需要时引用该组件避免重复的codeing

3.但是在Vue开发中很多是部分结构一样,如在一个Vue应用中每个页面整体外围框架相同但是内容各有差异(header,body,footer结构一样,但是内容差异)

4.这时候可以将通用的结构封装起来,将不同的内容通过Vue插槽分发到指定的位置,即可避免复制同样的代码提高开发效率

Vue插槽有一下几种

1.单个插槽(最基本的插槽分发)

例如每个模块样式都继承一下基本的结构

<div class="box">        <div class="box-body">                    </div></div>
这样每次新增一个样式模块时都要写此结构的代码,body里的内容是不一样的

于是便可以将其做成组件<box></box>,将不同的内容分发到body中即可

<div class="box">        <div class="box-body">            <slot>无分发内容时显示</slot>        </div></div>
使用时在父组件中如下调用

<father>        <box>            some code        </box></father>
2.具名插槽(顾名思义带有名字的插槽)

框架中需要分发到指定的位置,例如不同的位置有不同的样式做处理

<div class="box">        <div class="box-header"></div>        <div class="box-body"></div>        <div class="box-footer"></div></div>
此时就需要具名插槽将内容分别分发到header,boxy,footer

<div class="box">        <div class="box-header">            <slot name="header"></slot>        </div>        <div class="box-body">            <slot name="body"></slot>        </div>        <div class="box-footer">            <slot name="footer"></slot>        </div></div>
子组件中的接受插槽有唯一的name对应,表示不同的插槽,父组件中使用时对应不同的名字即可

<father>        <box>            <h5 slot="header">标题</h5>            <div slot="body">some code</div>            <div slot="footer">some code</div>        </box></father>
此时父组件中内容会按照对应的name分发到子组件中指定的位置


一个大型的单页应用良好的结构可以使用插槽分发达到不同页面渲染出来有规则的页面结构,减少页面结构复杂度

后期还能够更加高效的维护代码