您现在的位置是:亿华云 > 系统运维
何时何地使用 Vue 的作用域插槽
亿华云2025-10-02 18:42:10【系统运维】8人已围观
简介Vue插槽是一种将内容从父组件注入子组件的绝佳方法。下面是一个基本的示例,如果我们不提供父级的任何slot位的内容,刚父级<slot>中的内容就会作为后备内容。//ChildCompone
Vue插槽是何时何地一种将内容从父组件注入子组件的绝佳方法。
下面是使用一个基本的示例,如果我们不提供父级的作用任何slot位的内容,刚父级<slot>中的域插内容就会作为后备内容。
// ChildComponent.vue <template> <div> <slot> Fallback Content </slot> </div> </template>然后在我们的何时何地父组件中:
// ParentComponent.vue <template> <child-component> Override fallback content </child-component> </template>编译后,我们的使用DOM将如下所示。
<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。作用
在不更改默认后备内容的情况下,云服务器提供商我们可以像这样轻松实现此组件。
// ParentComponent.vue <template> <div> <article-header /> </div> </template>在浏览器中,会显示 title。
虽然我们可以通过向槽中添加模板表达式来快速地更改槽中的内容,但如果我们想从子组件中渲染info.description,会发生什么呢?
我们想像用下面的这种方式来做:
// Doesnt work! <template> <div> <article-header> { { info.description }} </article-header> </div> </template>但是,这样运行后会报错 :TypeError: Cannot read property ‘description’ of undefined。
这是因为我们的父组件不知道这个info对象是什么。
那么我们该如何解决呢?
引入作用域插槽
简而言之,作用域内的插槽允许我们父组件中的插槽内容访问仅在子组件中找到的数据。 例如,我们可以使用作用域限定的插槽来授予父组件访问info的权限。
我们需要两个步骤来做到这一点:
使用v-bind让slot内容可以使用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>最终的效果如下:
总结
尽管Vue 作用域插槽是一个非常简单的概念-让插槽内容可以访问子组件数据,这在设计出色的组件方面很有用处。通过将数据保留在一个位置并将其绑定到其他位置,管理不同状态变得更加清晰。
~完,我是刷碗智,我要去刷碗了,骨得白
作者:Ashish Lahoti 译者:前端小智 来源:codingnconcept
原文:https://learnvue.co/2021/03/when-why-to-use-vue-scoped-slots/
很赞哦!(76492)