如何将命名插槽插入父组件 [英] How to insert named slots into parent components
问题描述
命名插槽在覆盖组件的部分时非常有用,如下所示:
<警告><template slot="text">自定义警告文本!</template></警告>
如何使用命名插槽覆盖父组件中的 warning
组件部分,上一级?
<template slot="text">自定义警告文本!</template></component-with-a-warning>
我在 JS Fiddle 中更好地说明了这个问题.https://jsfiddle.net/madhazelnut/pdzoeqj0/
如果我正确理解您的问题,您希望将一个组件包装在另一个组件中,并且能够从定义在组件上的插槽中选择指定内部组件的插槽外部组件.
也可以通过向其添加 slot="name"
属性来渲染到另一个组件的插槽内,就像其他任何组件一样要在插槽中呈现的组件.
Vue.component('warning', {模板:'#警告',});Vue.component('包装警告', {模板:'#wrapped-warning',});新的 Vue({el: '#app',});
.warning {背景颜色:金色;边距:10px 0;}
<script src="https://unpkg.com/vue"></script><模板 id="警告"><div class="警告"><h1><slot name="heading"></slot></h1><div><slot name="text"></slot></div>
</模板><template id="wrapped-warning"><警告><slot name="heading" slot="heading">默认包装标题</slot><slot name="text" slot="text">默认换行文本</slot></警告></模板><div id="应用程序"><wrapped-warning></wrapped-warning><包装警告><template slot="heading">覆盖的标题</template><template slot="text">覆盖的文本</template></wrapped-warning>
Named slots are very useful in overriding sections of a component, like so:
<warning> <template slot="text">Custom warning text!</template> </warning>
How does one use named slots to override sections of warning
component within a parent component, one level up?
<component-with-a-warning>
<template slot="text">Custom warning text!</template>
</component-with-a-warning>
I illustrated this problem better in a JS Fiddle. https://jsfiddle.net/madhazelnut/pdzoeqj0/
If I understand your question correctly, you want to wrap a component inside another component and be able to optionally specify the slots of the inner component from slots defined on the outer component.
A <slot>
can also be rendered inside the slot of another component by adding the slot="name"
attribute to it, just like you would any other component that you want to render within a slot.
Vue.component('warning', {
template: '#warning',
});
Vue.component('wrapped-warning', {
template: '#wrapped-warning',
});
new Vue({
el: '#app',
});
.warning {
background-color: gold;
margin: 10px 0;
}
<script src="https://unpkg.com/vue"></script>
<template id="warning">
<div class="warning">
<h1><slot name="heading"></slot></h1>
<div><slot name="text"></slot></div>
</div>
</template>
<template id="wrapped-warning">
<warning>
<slot name="heading" slot="heading">Default wrapped heading</slot>
<slot name="text" slot="text">Default wrapped text</slot>
</warning>
</template>
<div id="app">
<wrapped-warning></wrapped-warning>
<wrapped-warning>
<template slot="heading">Overridden heading</template>
<template slot="text">Overridden text</template>
</wrapped-warning>
</div>
这篇关于如何将命名插槽插入父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!