【vue3】匿名插槽,具名插槽,作用域插槽,动态插槽

注意!

匿名插槽有name值,为default

  • 匿名插槽有name值,为default
  • 作用域插槽—可以把子组件的值传给父组件使用
  • v-slot: 可以简写成 #

//父级
<template>

    <Com9>
        <template v-slot>
            这里是匿名插槽
        template>
        <template #header>
            这里是具名插槽-header
        template>
        <template v-slot:footer>
            这里是具名插槽-footer
        template>

        <template v-slot:namespace="{list,test}">
            <p v-for="(item, index) in list" :key="index">
                这是作用域插槽---{{ item?.name }}---{{ test }}
            p>
        template>

        <template #[slotName]>
            <p>这里是动态插槽---{{ slotName }}p>
        template>
    Com9>
    <button @click="changeSlot('header')">插入headerbutton>
    <button @click="changeSlot('default')">插入mainbutton>
    <button @click="changeSlot('footer')">插入footerbutton>

template>

<script setup lang='ts'>
    import { ref,reactive } from 'vue'
    import Com9 from '../components/MySlot.vue'

    let slotName = ref<string>('header')
    const changeSlot = (string:string) =>{
        slotName.value = string
    }


script>
<style scoped lang='scss'>

style>

//子集
<template>

    <div class="header">
        <slot name="header">slot>
    div>
    <div class="main">
        <slot>slot>

        
        <slot :list="person" :test="'test'" name="namespace">slot>
    div>
    <div class="footer">
        <slot name="footer">slot>
    div>

template>

<script setup lang='ts'>
    import { reactive } from 'vue'

    type tobj = {
        name:string,
        age:number
    }

    const person = reactive<tobj []>([
        {
            name:'张三',
            age:12
        },
        {
            name:'李四',
            age:18
        },
        {
            name:'小明',
            age:18
        },
        {
            name:'小红',
            age:18
        }
    ])

script>
<style scoped lang='scss'>
.header{
    width: 400px;
    min-height: 100px;
    background-color: red;
    padding: 16px;
}
.main{
    width: 400px;
    min-height: 100px;
    background-color: rgb(0, 174, 255);
    padding: 16px;
}
.footer{
    width: 400px;
    min-height: 100px;
    background-color: rgb(255, 196, 0);
    padding: 16px;
}
style>

你可能感兴趣的:(vue3,javascript,前端,vue.js)