插槽
作用: 让父组件可以想子组件指定位置插入HTML
结构
也是一种组件间的通信方式, 适用于: 父 => 子
分类:
- 默认插槽
- 具名插槽
- 作用域插槽
默认插槽
- 代码示例
html
<!-- 父组件中 -->
<Demo>
<div>HTML结构</div>
</Demo>
<!-- 子组件中 -->
<template>
<div>
<slot>当组件没有传递具体的结构时展示</slot>
</div>
</template>
具名插槽
- 代码示例
html
<!-- 父组件中 -->
<Demo>
<template slot="header">
<div>HTML结构1</div>
</template>
<template v-slot:footer>
<div>HTML结构2</div>
</template>
</Demo>
<!-- 子组件中 -->
<template>
<div>
<slot name="header">当组件没有传递具体的结构时展示</slot>
<slot name="footer">当组件没有传递具体的结构时展示</slot>
</div>
</template>
作用域插槽
说明: 数据在子组件中, 但根据数据生成的结构要在父组件中决定, 需要在父组件中获取子组件中的数据进行插槽内容渲染
可结合具名插槽使用
- 代码示例
html
<!-- 父组件中 -->
<Demo>
<template scope="data">
<div>{{data.msg}}</div>
</template>
</Demo>
<Demo>
<template scope="{msg}">
<div>{{msg}}</div>
</template>
</Demo>
<Demo>
<template slot-scope="{msg}">
<div>{{msg}}</div>
</template>
</Demo>
<!-- 子组件中 -->
<template>
<div>
<slot :msg="data">当组件没有传递具体的结构时展示</slot>
</div>
</template>