vue插槽介绍

184 阅读1分钟

vue插槽分为三类:匿名插槽、具名插槽、作用域插槽

1. 匿名插槽

子组件定义了solt,但未提供名字,这就是匿名插槽,也叫做默认插槽,只要出现的父组件中,未指定插槽名字的内容,都会默认放到匿名插槽里。

  • 在父组件中
<template>
    <div>
        <myComponent>要被放入插槽中的内容</myComponent>
    </div>
</template>
  • 在子组件中
<template>
    <div>
        <slot><slot>//匿名插槽(显示父组件传递过来的内容)
    </div>
</template>

2. 具名插槽

所谓具名插槽,就是给插槽命了名字,父组件放进来的内容,需要指定插槽的名称,这个时候才会被分发到这个具名插槽中。

  • 父组件中
<template>
    <div>
        <myComponent>
            <template v-slot:slot1><!-- 这个会放到solt1中 -->
                <p>放入子组件中slot1中的插槽中</p>
            </template> 
        </myComponent>
    </div>
</template>
  • 子组件中
<template>
    <div>
        <slot name='slot1'><slot><!-- 名为“slot1”的具名插槽 -->
    </div>
</template>

3. 作用域插槽

让父组件中插槽内容能够访问子组件中才有的数据

  • 父组件中
<hello-word>
    // v-slot:(插槽名称)=(数据形参)
    <template v-slot:text="data">
      <p>姓名: {{ data.user.name }}</p>
      <p>年龄: {{ data.user.age }}</p>
    </template>
</hello-word>
  • 子组件中
    // text 插槽名字  user 插槽中数据
    <slot name="text" :user="user"></slot>