关于javascript:如何使用-Vue-命名插槽创建多个模板插槽

9次阅读

共计 2288 个字符,预计需要花费 6 分钟才能阅读完成。

作者:Matt Maribojoc
译者:前端小智
起源:stackabuse

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

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试残缺考点、材料以及我的系列文章。

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

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

// 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 中应用命名插槽有两个步骤:

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

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

为了给咱们的 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 默认的内容。

要解决这个问题,能够应用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>

再次运行:

应用 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 中传递所有这些信息。

如果查看 DOM,能够看到应用 v-slot 的模板将内容正确地插入到正确的地位。

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


代码部署后可能存在的 BUG 没法实时晓得,预先为了解决这些 BUG,花了大量的工夫进行 log 调试,这边顺便给大家举荐一个好用的 BUG 监控工具 Fundebug。

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

交换

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

本文 GitHub https://github.com/qq44924588… 已收录,有一线大厂面试残缺考点、材料以及我的系列文章。

正文完
 0