How to insert named slots into parent components

耗尽温柔 提交于 2021-02-11 09:17:53

问题


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/


回答1:


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>


来源:https://stackoverflow.com/questions/50548261/how-to-insert-named-slots-into-parent-components

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!