什么时候何地使用 Vue 的做用域插槽

做者:Ashish Lahoti
译者:前端小智
来源:codingnconcept
点赞再看,微信搜索 大迁世界,B站关注【 前端小智】这个没有大厂背景,但有着一股向上积极心态人。本文 GitHub https://github.com/qq44924588... 上已经收录,文章的已分类,也整理了不少个人文档,和教程资料。**

image.png

Vue插槽是一种将内容从父组件注入子组件的绝佳方法。前端

下面是一个基本的示例,若是咱们不提供父级的任何slot位的内容,刚父级<slot>中的内容就会做为后备内容。vue

// ChildComponent.vue
<template>
  <div>
     <slot> Fallback Content </slot>
  </div>
</template>

而后在咱们的父组件中:git

// ParentComponent.vue
<template>
   <child-component>
      Override fallback content
   </child-component>
</template>

编译后,咱们的DOM将以下所示。github

<div> Override fallback content </div>

咱们还能够未来自父级做用域的任何数据包在在 slot 内容中。 所以,若是咱们的组件有一个名为name的数据字段,咱们能够像这样轻松地添加它。面试

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

<script>
export default {
   data () {
     return {
       text: 'hello world',
     }
   }
}
</script>

为何咱们须要做用域插槽

咱们来看另外一个例子,假设咱们有一个ArticleHeader组件,data 中包含了一些文章信息。浏览器

// ArticleHeader.vue
<template>
  <div>
    <slot v-bind:info="info"> {{ info.title }} </slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      info: {
        title: 'title',
        description: 'description',
      },
    }
  },
}
</script>

咱们细看一下 slot 内容,后备内容渲染了 info.title微信

在不更改默认后备内容的状况下,咱们能够像这样轻松实现此组件。ide

// ParentComponent.vue
<template>
  <div>
    <article-header />
  </div>
</template>

在浏览器中,会显示 title工具

image.png

虽然咱们能够经过向槽中添加模板表达式来快速地更改槽中的内容,但若是咱们想从子组件中渲染info.description,会发生什么呢?spa

咱们想像用下面的这种方式来作:

// Doesn't work!
<template>
  <div>
    <article-header>
        {{ info.description }}
    </article-header>
  </div>
</template>

可是,这样运行后会报错 :TypeError: Cannot read property ‘description’ of undefined

这是由于咱们的父组件不知道这个info对象是什么。

那么咱们该如何解决呢?

引入做用域插槽

简而言之,做用域内的插槽容许咱们父组件中的插槽内容访问仅在子组件中找到的数据。 例如,咱们可使用做用域限定的插槽来授予父组件访问info的权限。

咱们须要两个步骤来作到这一点:

  • 使用v-bindslot内容可使用info
  • 在父级做用域中使用v-slot访问slot属性

首先,为了使info对父对象可用,咱们能够将info对象绑定为插槽上的一个属性。这些有界属性称为slot props

// ArticleHeader.vue
<template>
  <div>
    <slot v-bind:info="info"> {{ info.title }} </slot>
  </div>
</template>

而后,在咱们的父组件中,咱们可使用<template>v-slot指令来访问全部的 slot props。

// ParentComponent.vue 
<template>
  <div>
    <child-component>
      <template v-slot="article">
      </template>
    </child-component>
  </div>
</template>

如今,咱们全部的slot props,(在咱们的示例中,仅是 info)将做为article对象的属性提供,而且咱们能够轻松地更改咱们的slot以显示description内容。

// ParentComponent.vue 
<template>
  <div>
    <child-component>
      <template v-slot="article">
        {{ article.info.description }}
      </template>
    </child-component>
  </div>
</template>

最终的效果以下:

image.png

总结

尽管Vue 做用域插槽是一个很是简单的概念-让插槽内容能够访问子组件数据,这在设计出色的组件方面颇有用处。 经过将数据保留在一个位置并将其绑定到其余位置,管理不一样状态变得更加清晰。

~完,我是刷碗智,我要去刷碗了,骨得白


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

原文:https://learnvue.co/2021/03/w...

交流

文章每周持续更新,能够微信搜索「 大迁世界 」第一时间阅读和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 已经收录,整理了不少个人文档,欢迎Star和完善,你们面试能够参照考点复习,另外关注公众号,后台回复福利,便可看到福利,你懂的。

相关文章
相关标签/搜索