一、默认插槽(最简单的单个插槽)
- 在父组件中,定义插槽填充的内容
默认插槽的两种写法
<template>
<div>
<comp>
<div>I am default slot value</div>
</comp>
<comp>
<template v-slot:default>
<div>I am default slot value</div>
</template>
</comp>
<comp>
<template #default>
<div>I am default slot value</div>
</template>
</comp>
</div>
</template>
<script setup>
import comp from "@/components/comp.vue";
</script>
- 在子组件中,定义插槽的位置
可以定义 no data ,当插槽没有内容时填充展示
<template>
<div>
<slot> slot no data show </slot>
</div>
</template>
二、具名插槽(多个插槽时,按照插槽名字区分插槽)
- 在父组件中,定义插槽填充的内容和插槽名字
注意:v-slot 只能定义在 template 标签上
<template>
<div>
<comp>
<template v-slot:header>
<p>fill heaer</p>
</template>
<template #main>
<p>fill main (vue3)</p>
</template>
<template v-slot:footer>
<p>fill footer</p>
</template>
</comp>
</div>
</template>
<script setup>
import comp from "@/components/comp.vue";
</script>
- 在子组件中,定义插槽的位置,通过 name 属性区分插槽
<template>
<div>
<slot name="header"> slot no data show header</slot>
<slot name="main"> slot no data show main</slot>
<slot name="footer"> slot no data show footer</slot>
</div>
</template>
三、作用域插槽(父组件在插槽区域内可以使用 子组件通过插槽传递过来的变量)
父组件和子组件的插槽区域变量只在当前组件内有效,但是可以通过作用域插槽的方式让父组件可以使用子组件的变量
- 在父组件中,定义插槽填充的内容和插槽名字,接收参数
注意:只能在插槽 template 标签区域内使用接收的参数
<template>
<div>
<comp>
<template v-slot:default="{userInfo}">
<div>{{userInfo.username}}</div>
<div>{{userInfo.password}}</div>
</template>
</comp>
<comp>
<template #default="{userInfo}">
<div>{{userInfo.username}}</div>
<div>{{userInfo.password}}</div>
</template>
</comp>
</div>
</template>
<script setup>
import comp from "@/components/comp.vue";
</script>
- 在子组件中,定义插槽的位置,定义和传递参数
<template>
<div>
<slot :userInfo="userInfo"> slot no data show </slot>
</div>
</template>
<script setup>
import { ref } from 'vue';
const userInfo = ref({
username: 'alias',
password: '123456',
})
</script>
网友评论