vue 插槽的使用

93 阅读1分钟

1.基本演示

js
    //父组件
    <template>
        <myInput>
            用 slot 开启插槽
        </myInput>
    </template>
    <script>
    import myInput from './components/myInput.vue'
    export default {
        components: {
            myInput,
        }
    }
    </script>
    
    //子组件
    <template>
        输入文本 <input type="text"> 
        <!-- 在组件中书写 slot 在父组件可以 使用文本信息-->
        <slot></slot>
    </template>

image.png

2.具名插槽

具名插槽允许你在父组件中指定子组件内容插入的位置。在子组件中,你可以使用<slot>元素并为其添加一个name属性,以指定插槽的名称。在父组件中,你可以使用<template>元素来定义插槽的位置,并使用v-slot指令来指定插槽的名称。

js
    // 父组件
    <template>
        <myInput>
            <template #default> 
                没有名字的插槽
            </template>
            <template #showmsg>
                <p>showmag 的文本</p>
            </template>
            <template #time>
                <p>time 的文本</p>
            </template>
        </myInput>
    </template>
    <script>
    import myInput from './components/myInput.vue'
    export default {
        components: {
            myInput,
        }
    }
    </script>
    
    // 子组件
    <template>
        输入文本 <input type="text"> 

        <slot name="time"></slot>
        <slot name="showmsg"></slot>
        <slot></slot>
    </template>

3.作用域插槽

作用域插槽其实就是带数据的插槽,即带参数的插槽,简单的来说就是子组件提供给父组件的参数,该参数仅限于插槽中使用,父组件可根据子组件传过来的插槽数据来进行不同的方式展现和填充插槽内容。

js
    // 子组件
    <template>
        输入文本 <input type="text">
        <!-- 作用域插槽第一步,绑定一些数据 -->
        <slot name="time" :data="time"></slot>
        <slot name="showmsg" :age="age"></slot>
    </template>

    <script>
    export default {
        data() {
            return {
                time: '2023/11/25',
                age: 18
            }
        }
    }
    </script>
    
    // 父组件
    <template>
    <myInput>
        <template #showmsg="age">
            <p>showmag 的文本 --- {{ age.age }}</p>
        </template>
        <template #time="time">
            <p>time 的文本 --- {{ time.data }}</p>
        </template>
    </myInput>
</template>
<script>
import myInput from './components/myInput.vue'
export default {
    components: {
        myInput,
    }
}
</script>

image.png