如何使用 Vue 命名插槽建立多个模板插槽?

做者:Matt Maribojoc
译者:前端小智
来源:stackabuse

有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。前端

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及个人系列文章。vue

Vue 插槽容许将父组件中的内容注入到子组件中。git

这是最基本的示例,若是咱们不提供父级的任何slot 内容,则咱们将<slot>放在其中的任何内容都会做为后备内容。github

// ChildComponent.vue
<template>
  <div>
     <slot> 后备内容 </slot>
  </div>
</template>

你组件代码:面试

// ParentComponent.vue
<template>
   <child-component>
      替换 slot 的默认内容
   </child-component>
</template>

编译后,咱们的 DOM 将以下所示微信

<div> 替换 slot 的默认内容 </div>

咱们还能够将父组做用域内的任何数据写在 slot 区域中。 例如,父组件有一个名为title的数据字段,咱们可使用如下代码将其注入到子组件中:工具

// ParentComponent.vue

<template>
   <child-component>
      {{ title }} 
   </child-component>
</template>

<script>
export default {
   data () {
     return {
       title: '这会传递给子组件',
     }
   }
}
</script>

为何咱们须要命名插槽

在Vue中使用命名插槽有两个步骤:spa

  1. 使用name属性从子组件中命名 slot
  2. 使用v-slot指令从父组件向这些命名插槽提供内容

默认状况下,不给插槽显式的name属性时,它有默认名字是defaultdebug

为了给咱们的 slot 起个名字,<slot>元素具备一个特殊的name属性,可让咱们在多个插槽之间进行区分。设计

在下面的 Article.vue 中,咱们命名三个 slot

// Article.vue - Child Component
<template>
  <div>
    <slot name="title"> 默认 title </slot>
    <slot name="content"> 默认 content </slot>
    <slot name="comments"> 默认 comments</slot>
  </div>
</template>

而后,在父组件中,咱们能够在<template>元素上使用v-slot指令指定咱们想要注入内容的slot

// ParentComponent.vue
<template>
  <div>
    <child-component>
      <template> 个人 Title </template>
      <template> 个人 Content </template>
      <template> 个人 Comments </template>
    </child-component>
  </div>
</template>

由于这是没有指定 slot 的名称,因此显示的是 slot 默认的内容。

image.png

要解决这个问题,可使用v-slot,指定的名称要确保名称与咱们在子组件中声明的名称彻底匹配。

<template>
  <div>
    <child-component>
      <template v-slot:title> 个人 title </template>
      <template v-slot:content> 个人 content </template>
      <template v-slot:comments> 个人 comments </template>
    </child-component>
  </div>
</template>

再次运行:

image.png

使用 Vue 命名插槽有什么意义

命名槽让咱们可使用多个槽,可是为何这对咱们Vue开发人员有用呢。

简而言之,它使咱们能够更好地组织开发代码,还能够编写更具扩展性的代码。

就我的而言,我认为最重要的是,它容许咱们在代码上使用插槽,从而使样式设计变得更加容易。 在咱们的示例中,Article.vue子组件只有三个插槽,可是在实际应用中,这些插槽看起来更像这样,以便咱们的组件能够向每一个部分添加CSS样式。

<template>
  <div>
    <div class="title">
      <h1>
        <slot name="title"> 默认 Title </slot>
      </h1>
    </div>
    <div class="content">
      <p>
        <slot name="content"> 默认  Content </slot>
      </p>
    </div>
    <div class="comments">
      <slot name="comments"> 默认  Comments </slot>
    </div>
  </div>
</template>

在此示例中,更容易理解为何咱们须要多个 slot。 因为咱们注入的内容是经过不一样的<div><p>和DOM元素彼此分隔的。 没法在一个slot中传递全部这些信息。

image.png

若是检查DOM,能够看到使用v-slot的模板将内容正确地插入到正确的位置。

image.png

~完,我是刷碗智,去刷碗了,下期见!


代码部署后可能存在的BUG无法实时知道,过后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给你们推荐一个好用的BUG监控工具 Fundebug

原文:
https://learn.co/2021/04/usin...

交流

有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq44924588... 已收录,有一线大厂面试完整考点、资料以及个人系列文章。

相关文章
相关标签/搜索