How does <slot></slot>
and scoped slots work to receive descent from another component and pass props
to descending elements?
When a component has a slot (s), it can inject content into it from the parent component, without the need to use 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><divid="app">
<meu-componente>
{{ message }}
</meu-componente>
</div>
Notice that message
belongs to the outside component (the root / app of Vue, in this case), while the header renders the value of an internal variable to the component.
How to know what content should go to that slot in case one component has multiple?
You can use multiple slots simply by giving a name attribute to each, and passing the content into an HTML tag with the slot
attribute pointing to that name. In the definition of the component is thus, 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>
Can a slot have initial offspring that is replaced by future offspring if there is no v-if or v-show to use?
Yes! If you do not pass a content to a particular slot from the external component, the contents of the slot defined in the built-in component will be displayed. It works as a default content.