How does the <slot></slot>
and scoped slots to receive offspring from another component and pass props
to the descending elements?
When a component has a slot(s), it is possible to inject content into it from the parent component without having to props
. For example:
var MeuComponente = Vue.component('meu-componente', {
template: '<div class="meu-componente"><h1>{{ header }}</h1><slot></slot></div>',
data() { return { header: 'Isto vem de dentro' } }
});
new Vue({
el: '#app',
data: {
message: 'Isto vem de fora'
}
});
<script src="https://unpkg.com/vue"></script>
<div id="app">
<meu-componente>
{{ message }}
</meu-componente>
</div>
Notice that message
belongs to the outside component (the Vue root/app in this case), while the header renders the value of an internal variable to the component.
How to know which content should go to which slot in case a component has multiple?
You can use multiple slots by simply giving a name attribute to each, and passing the content on an HTML tag with attribute slot
pointing to that name. In the component definition it looks like this, for example:
<h1>{{ header }}</h1>
<slot name="abaixo-do-h1"></slot>
<h2>Outro header</h2>
<slot name="abaixo-do-h2"></slot>
In use it looks like this:
<meu-componente>
<div slot="abaixo-do-h1>Isto vai abaixo do h1</div>
<div slot="abaixo-do-h2>Isto vai abaixo do h2</div>
</meu-componente>
A slot can have initial offspring that is replaced by future offspring if there is one without having to use a v-if or v-show?
Yes! If you do not pass content to a particular slot from the external component, the slot content defined in the internal component will be displayed. Acts as a content default.