插槽就是子組件中的提供給父組件使用的一個占位符,用<slot></slot> 表示,父組件可以在這個占位符中填充任何模板代碼,如 HTML、組件等,填充的內容會替換子組件的<slot></slot>標簽,
1 匿名插槽
(1) 在子組件放置一個插槽,mytest.vue
<template>
<div>
<slot>我這里設定默認值</slot>
</div>
</template>
(2) 父組件使用插槽,在父組件給這個插槽填充內容,如果不設定內容就會參考子組件的內容
<myslot>
<template v-slot>
<div>我是插槽的值</div>
</template>
</myslot>
2 具名插槽
具名插槽其實就是給插槽取個名字,一個子組件可以放多個插槽,而且可以放在不同的地方,而父組件填充內容時,可以根據這個名字把內容填充到對應插槽中.
<template>
<div>
<slot name="header"></slot>
<slot>我這里設定默認值</slot>
<slot name="footer"></slot>
</div>
</template>
父組件使用需對應名稱.
<myslot>
<template v-slot:header>
<div>我是插槽header的值</div>
</template>
<template v-slot>
<div>我是插槽的值</div>
</template>
<template v-slot:footer>
<div>我是插槽footer的值</div>
</template>
</myslot>
這里還可以進行簡寫
<myslot>
<template #header>
<div>我是插槽header的值</div>
</template>
<template #default>
<div>我是插槽的值</div>
</template>
<template #footer>
<div>我是插槽footer的值</div>
</template>
</myslot>
3 作用域插槽
在子組件動態系結引數 派發給父組件的slot去使用.
<template>
<div>
<slot name="header"></slot>
<div :key="item" v-for="item in 100">
<slot v-bind:data="https://www.cnblogs.com/lotusflower/archive/2022/08/08/item">我這里設定默認值</slot>
</div>
<slot name="footer"></slot>
</div>
</template>
通過結構方式取值:
<myslot>
<template #header>
<div>我是插槽header的值</div>
</template>
<template #default="{ data }">
<div>我是插槽傳過來的值{{ data }}</div>
</template>
<template #footer>
<div>我是插槽footer的值</div>
</template>
</myslot>
4 動態插槽
插槽可以是一個變數名
<template>
<div>
<myslot>
<template #[name]>
<div>我是變數插槽{{name}}</div>
</template>
</myslot>
</div>
</template>
<script setup lang="ts">
import myslot from './components/test_slot.vue'
import { ref } from 'vue'
const name = ref<string>('header')
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/501289.html
標籤:其他
