匿名插槽
一个不命名的插槽。
Dialog/index.vue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| <template> <div> <main class="main"> <div v-for="(item, index) in data" :key="index"> <!-- 直接这样定义就是匿名插槽 --> <!-- 加上v-bind的属性就是插槽作用域,父组件进行插槽使用时可以获取这里的值 --> <slot :data="item" :index="index"></slot> </div> </main> </div> </template>
<script setup lang="ts"> import { reactive } from 'vue'
type names = { name: string, age: number }
const data = reactive<names[]>([ { name: "yajue", age: 24 }, { name: "knn", age: 300 }, { name: "snnn", age: 30 }, { name: "bnkrg", age: 17 } ]) </script>
<style scoped lang="scss"> .main { height: 300px; background-color: green; color: white; } </style>
|
App.vue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <div> <Dialog> <!-- 使用匿名插槽 --> <!-- v-slot可以取插槽作用域的值 --> <!-- <template v-slot="{ data, index }"> --> <!-- 匿名插槽的简写需要写成#default --> <template #default="{ data, index }"> <div> {{ index }}. {{ data.name }} ---- {{ data.age }} </div> </template> </Dialog> </div> </template>
<script setup lang="ts"> import Dialog from "@/components/Dialog/index.vue" </script>
|
具名插槽
被起了名字的插槽。
Dialog/index.vue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <template> <div> <header class="header"> <!-- 加上name属性就是具名插槽,名字是name的值 --> <slot name="header" :data="111"></slot> </header> </div> </template>
<style scoped lang="scss"> .header { height: 200px; background-color: red; color: white; } </style>
|
App.vue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <div> <Dialog> <!-- 使用具名插槽 --> <!-- <template v-slot:header> --> <!-- v-slot可以被简写成井号# --> <template #header="{ data }"> <div> header{{ data }} </div> </template> </Dialog> </div> </template>
<script setup lang="ts"> import Dialog from "@/components/Dialog/index.vue"
</script>
|
动态插槽
使用变量作为名的插槽。
Dialog/index.vue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <div> <footer class="footer"> <slot name="footer"></slot> </footer> </div> </template>
<style scoped lang="scss"> .footer { height: 200px; background-color: blue; color: white; } </style>
|
App.vue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <div> <Dialog> <!-- 使用动态插槽 --> <template #[name]> <div> 草 </div> </template> </Dialog> </div> </template>
<script setup lang="ts"> import { ref } from 'vue' import Dialog from "@/components/Dialog/index.vue"
let name = ref("footer") </script>
|