您现在的位置是:亿华云 > 域名
如何使用 Vue 命名插槽创建多个模板插槽?
亿华云2025-10-03 15:40:45【域名】7人已围观
简介Vue 插槽允许将父组件中的内容注入到子组件中。这是最基本的示例,如果我们不提供父级的任何slot 内容,则我们将放在其中的任何内容都会作为后备内容。//ChildComponent.vue<t
Vue 插槽允许将父组件中的何使内容注入到子组件中。
这是命名模板最基本的示例,如果我们不提供父级的插槽创建插槽任何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中使用命名插槽有两个步骤:
使用name属性从子组件中命名 slot 使用v-slot指令从父组件向这些命名插槽提供内容默认情况下,不给插槽显式的何使name属性时,它有默认名字是命名模板default。
为了给我们的插槽创建插槽 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>然后,在父组件中,云南idc服务商我们可以在元素上使用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的模板将内容正确地插入到正确的位置。
~完,我是刷碗智,去刷碗了,下期见!
作者:Matt Maribojoc 译者:前端小智 来源:stackabuse
原文:https://learn.co/2021/04/using-vue-named-slots-to-create-multile-template-slots/
本文转载自微信公众号「大迁世界」,可以通过以下二维码关注。转载本文请联系大迁世界公众号。
很赞哦!(4833)
下一篇: 数据中心的电力监控和计量解决方案