Vue插槽使用
概述
插槽就是子组件中用slot标签定义的预留位置,可以设置name属性,也可以不设置name属性,设置name的叫具名插槽
,不设置name的的叫不具名插槽
,在父组件中使用子组件时候可以在使用子组件的标签内
通过声明插槽名
或不声明插槽名
的方式往子组件中的具名插槽
或者不具名插槽
写入html代码
。
插槽使用的关键在于:在父组件中使用子组件标签的时候可以往子组件内写入html代码
。
使用步骤
- 子组件中定义插槽
- 父组件使用子组件时往插槽写入代码
核心伪代码
父组件视图中:
<子组件名>
<!--往插槽写入html代码-->
<!--写入具名插槽1-->
<div slot="插槽名1">
这段html连带div会写入到子组件插槽名1
</div>
<!--写入具名插槽2-->
<template slot="插槽名2">
由于template不会被解析,所以这段html只有这段文字会写入到子组件插槽名2
</template>
<!-- 写入不具名插槽 -->
<template>
这段文字会写入不具名插槽
</template>
</子组件名>
子组件视图:
<h2>子组件</h2>
<!--定义插槽-->
<!--slot设置了name属性为具名插槽,不设置name属性为不具名插槽-->
<!--具名插槽-->
<slot name="插槽名2"></slot>
<slot name="插槽名1"></slot>
<!--不具名插槽-->
<slot></slot>
总结:
- 插槽在子组件的视图中定义
子组件视图:
<h2>子组件</h2>
<!--slot设置了name属性为具名插槽,不设置name属性为不具名插槽-->
<!--具名插槽-->
<slot name="插槽名2"></slot>
<slot name="插槽名1"></slot>
<!--不具名插槽-->
<slot></slot>
- 父组件使用子组件标签时&#