Vue05---插槽、具名插槽、作用域插槽

目录

什么是插槽?

1、普通插槽

2、具名插槽

 3、作用域插槽


什么是插槽?

插槽就是子组件中提供给父组件的一个占位符,用<slot></slot>表示,父组件可以在使用子组件的时候在子组件内部加入任何内容,该内容将替换子组件的<slot></slot>

代码如下:

1、普通插槽

在子组件中插入slot标签

<template>
    <div>
        <span>我的名字叫:</span>
        <slot></slot>
    </div>
</template>

在父组件中传入要自定义显示的内容

<Child>
        <span>Lisa</span>
</Child>

效果:

2、具名插槽

给插槽起了个名字,可以实现子组件根据名称插入多个插槽的效果。

子组件用name定义插槽名字:

<template>
    <div>
        <slot name="header"></slot>
        <div class="content">content</div>
        <slot name="footer"></slot>
    </div>
</template>

 父组件使用v-slot来对应

<Child>
        <template v-slot:header>这是头部</template>
        <template v-slot:footer>这是尾部</template>
</Child>

效果

 3、作用域插槽

作用域插槽的主要作用是在书写插槽内容时可以获取到插槽作用域的值,通过父组件定于子组件数据的显示方式。

子组件

<template>
    <div>
        <slot name="header" :userName="userName" :userAge="userAge"></slot>
        <div class="content">content</div>
    </div>
</template>

<script>
    export default {
        name: "Child",
        data(){
            return{
                userName:"Lisa",
                userAge:'23',
            }
        }
    }
</script>

父组件:message接收的是子组件的参数

 <Child>
        <template v-slot:header="message">
            <div>{
   
   {message.userName}}</div>
            <div>{
   
   {message.userAge}}</div>
        </template>
</Child>

效果:

总结

 v-slot的出现是为了代替原有的slot和slot-scope
简化了一些复杂的语法。
一句话概括就是v-slot :后边是插槽名称,=后边是组件内部绑定作用域值的映射。

猜你喜欢

转载自blog.csdn.net/m0_37756431/article/details/123406857