###一、内容分发
1、是什么
一种过程,混合父组件内容和子组件模板的方式。
2、作用域
2.1、编译的数据应该绑定在父组件的数据中。
2.2、父组件的内容在父组件的作用域,子组件模板的内容在子组件作用域。
即:被分发的内容在父组件内编译。
<children v-model="message"></children>
,此处的message应该在子组件作用域内进行编译
###插槽有哪些
0、插槽
用<slot></slot>
作为原始内容的插槽。最初在slot中的任何内容都被视为备用内容,当没有插入的内容时才显示的备用内容
1、单个插槽
1.1、当子组件模板中只有一个没有属性的<slot>
标签时,父组件传入的整个内容都会插入到插槽所在的DOM位置。
1.2、代码
a、子组件childComponent
<template>
<div id="page-scroll-content">
<h2>子组件模板</h2>
<slot>我是slot,该不该显示呢?</slot>
</div>
</template>
b、父组件fatherComponent
<template>
<div>
<h2>父组件模板</h2>
// 此处是将2个div节点替换了slot的内容
<childComponent>
<div>我是父组件初始内容1</div>
<div>我是父组件初始内容</div>
</childComponent>
</div>
</template>
c、渲染结果:
<div class="fatherComponent">
<div>
<h2>父组件模板</h2>
<div>我是父组件初始内容1</div>
<div>我是父组件初始内容</div>
</div>
</div>
2、具名插槽(多插槽使用)
2.1、使用slot的name属性进行分发,此时可以有一个匿名插槽,用作备用插槽。
2.2、代码
a、子组件commonComponent;给slot标签添加name属性
<template>
<div id="childContainer">
<header>
<slot name="header"></slot>
<slot name="default"></slot>
<slot name="footer"></slot>
</header>
</div>
</template>
b、父组件mainComponent;给要传递的DOM添加‘slot=“对应的name名称”’
<template>
<commonComponent>
<p slot="header">头部信息</p>
<div>这是默认信息,若没有匹配片段是的备用插槽</div>
<div>这是默认信息,若没有匹配片段是的备用插槽</div>
<p slot="footer">页脚信息</p>
</commonComponent>
</template>
c、渲染结果
<div id="childContainer">
<header>
<p>头部信息</p>
</header>
<main>
<div>这是默认信息,若没有匹配片段是的备用插槽</div>
<div>这是默认信息,若没有匹配片段是的备用插槽</div>
</main>
<footer>
<p>页脚信息</p>
</footer>
</div>
3、作用域插槽
3.1、可传递数据,可重复使用。此用法类似于props
3.2、代码
3.2.1、父组件接收子组件数据
a、子组件scopeChild
<template>
<div id="scopeChild">
<slot text1="msg from scopeChild"></slot>
</div>
</template>
b、父组件scopeFather
<template>
<div id="scopeFather">
<socpeChild>
/*
* slot-scope为vue2.5+的新属性,低于此版本请使用scope
* slot-scope可以在任意元素、组件中使用
* slot-scope的值作为一个临时变量来接收子组件传递过来的props对象。
*/
<template slot-scope="childData">
<div>msg from father</div>
<div>{{childData.text1}}</div>
</template>
</scopeChild>
</div>
</template>
c、渲染结果
<div id="scopeFather">
<div id="scopeChid">
<div>msg from father</div>
<div>msg from scopeChild</div>
</div>
</div>
温馨提示:扫码可以提问、交流。本人有各个行业的小程序前端代码,如有需要也可以扫码留言哦。