一个简单的插槽
// 组件
<button>
<slot></slot>
</button>
// 使用
<v-button>你好</v-button>
<div class="img">
<v-button>
<img src="@/assets/th.jpg" alt="">
</v-button>
</div>
效果图:
具名插槽
// 组件
<button>
<slot name="icon"></slot>
<slot name="txt"></slot>
</button>
// 使用
<v-button>
<template #txt>
你好
</template>
</v-button>
<div class="img">
<v-button>
<template #icon>
<img src="@/assets/th.jpg" alt="">
</template>
</v-button>
</div>
具名插槽就是通过slot插槽的name属性,定义一个插槽的名字。使用的时候可以用v-slot加插槽名
或#加插槽名
标记要展示的插槽,通常用后者。
使用场景:一个组件有多处插槽,使用具名插槽区分。不带name的slot插槽默认
name='default'
作用域插槽
// 组件
<template #default="{ row }">
<slot :name="item.field" :row_data="row">
{{row[item.field]}}
</slot>
</template>
// 使用
<template #name="prop">
<a href="#" target="_black">我是超链接:{{ prop.row_data.name }}</a>
</template>
<template #edit="prop">
<vxe-button @click="edit(prop.row)">编辑</vxe-button>
</template>
作用域插槽让其他页面在使用组件的时候可以通过定义好的插槽prop访问到插槽内部的值,例如上述代码中的row_data
,插槽prop可以自定义名称。
使用场景:二次封装UI库中的组件时,例如:封装elementUI、ant-design-vue、vxe-table等,将解构出的
行数据
传给父级。
动态插槽名
<template v-for="(item,index) in columns" #[item.slots.edit]>
<div :key="index">
<slot :name="item.field"></slot>
</div>
</template>
动态插槽名通常和v-for
一起使用,循环生成插槽。
使用场景:表格有多列需要经过处理才能显示时,封装的表格可以对应列生成插槽。