插槽的用途就和它的名字一样:有一个缺槽,我们可以插入一些东西。
插槽 slot 通常用于两个父子组件之间
基本使用
子组件--Test1
<template>
<div>子组件1</div>
<slot></slot>
</template>
父组件--Test
<template>
<div>父组件</div>
<Test1>
<span>传递给子组件显示</span>
</Test1>
</template>
在子组件使用slot进行占位
具名插槽
<template>
<div>父组件</div>
<Test1>
<template v-slot:header>header</template>
<div>没有名字的插槽,默认为default</div>
<template #footer>footer</template>
</Test1>
</template>
<template>
<div>子组件1</div>
<header style="background-color: aqua;">
<slot name="header"></slot>
</header>
<slot></slot>
<footer style="background-color: skyblue;">
<slot name="footer"></slot>
</footer>
</template>
上段代码中我们添加了 3 个 slot 插槽,其中两个 slot 标签有一个 name 属性,用于定义每个插槽的名字
上段代码中有一个插槽没有添加 name 属性,这个时候 Vue 会隐式的将这个插槽命名为“default”
slot 有了名字,那么我们在父组件中传入内容时就要和名字关系对应起来,我们采用 v-slot:header 指令的形式找到对应的插槽,需要注意的是该指令需要作用在 template 元素上
v-slot:name 指令也有简写形式 #name
动态插槽名
let dynameName = 'header'
<Test1>
<!-- <template v-slot:[dynameName]> -->
<template #[dynameName]>
动态插槽名
</template>
</Test1>
作用域插槽传值
<template>
<div>父组件</div>
<Test1>
<template v-slot:header="cVal">header {{ cVal.msg }}</template>
<template #default="{msg}">
<div>{{msg}} 没有名字的插槽,默认为default</div>
</template>
<template #footer="{msg,color}">{{color}} footer {{ msg }}</template>
</Test1>
</template>
<template>
<div>子组件1</div>
<header style="background-color: aqua;">
<slot msg="h传值" color="aqua" name="header"></slot>
</header>
<slot msg="d传值"></slot>
<footer style="background-color: skyblue;">
<slot msg="f传值" color="skyblue" name="footer"></slot>
</footer>
</template>
本文含有隐藏内容,请 开通VIP 后查看