vue 新版slot(官方文档)

308 阅读2分钟

1.插槽内容

子组件:(slot-demo)

<div>
    <h3>slot-demo</h3>
    <slot></slot>
</div>

父组件使用,会将<slot></slot>替换为<div>something</div>,slot里面也可以设置默认值

<slot-demo>
  <div>something</div>
</slot-demo>

2.具名插槽的缩写 v-slot:替换为字符#

例如 v-slot:header 可以被重写为 #header

<template #header>
    <h1>Here might be a page title</h1>
</template>

然而,和其它指令一样,该缩写只在其有参数的时候才可用。这意味着以下语法是无效的:

<!-- 这样会触发一个警告 -->
<current-user #="{ user }">
  {{ user.firstName }}
</current-user>

如果你希望使用缩写的话,你必须始终以明确插槽名取而代之:

<current-user #default="{ user }">
  {{ user.firstName }}
</current-user>

3.具名插槽

template配合v-slot:/#使用 -->官方推荐

有时我们需要多个插槽。例如对于一个带有如下<base-layout>模板的组件, <slot> 元素有一个特殊的特性:name。这个特性可以用来定义额外的插槽,一个不带 name 的 <slot> 出口会带有隐含的名字“default”。

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

在向具名插槽提供内容的时候,我们可以在一个 <template> 元素上使用 v-slot:/# 指令,并以 v-slot 的参数的形式提供其名称:(注意 v-slot 只能添加在一个 <template> 上)

<base-layout>
  <template #header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template #footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

4.作用域插槽

将要渲染的currentUser组件,为了让 user 在父级的插槽内容可用,我们可以将 user 作为 元素的一个特性绑定上去,绑定在 元素上的特性被称为插槽 prop。

<template>
  <div>
    <h3>current-user组件</h3>
    <slot name="default" :user="user"></slot> <br />
    <slot name="age" :user="user"></slot>
  </div>
</template>
export default {
  data() {
    return {
      user: {
        name: 'lily',
        age: 18,
      }
    }
  }
}

现在在父级作用域中,我们可以给 v-slot 带一个值来定义我们提供的插槽 prop 的名字,可以使用任意你喜欢的名字,也可以使用解构赋值解构插槽 Prop

    <current-user>
      <template #default="slotProps">
        名字是:{{ slotProps.user.name }}
      </template>
      <template v-slot:age="obj">
        年龄是{{ obj.user.age }}
      </template>
      <template v-slot:age="{ user }">
        年龄是{{ user.age }}
      </template>
    </current-user>