Basic usage of component slots

You pass in templates

Example:

html:

<div id='app'>
    <alert-box>Warning 1</alert-box>
    <alert-box>Warning 2</alert-box>
    <alert-box></alert-box>
</div>
Copy the code

js:

Vue.component('alert-box', {
    template: ` < div > < strong > Error: < / strong > < slot > default < / slot > < / div > `,})Copy the code

Note: The default values are replaced, not shown together.

A named slot

The slot is matched by the slot name. Any slot that is not matched is placed in a default slot that has no name.

Example:

<div id='app'>
    <base-layout>
        <p slot='header'>Header information</p>
        <p>The default 1</p>
        <p>The default 2</p>
        <p slot='footer'>At the bottom of the information</p>
    </base-layout>

    <base-layout>
    <! Fill the slot with multiple pieces of text using template -->
    <! -- Template is just a temporary wrapper, not rendered to the page -->
        <template slot='header'>
            <p>Title Message 1</p>
            <p>Title Message 2</p>
        </template>
        <template>
            <p>The default 1</p>
            <p>The default 2</p>
        </template>
        <template slot='footer'>
            <p>Bottom Message 1</p>
            <p>Bottom Message 1</p>
        </template>
    </base-layout>
</div>
Copy the code

js:

Vue.component('base-layout', {
    template: ` 
      
`
,})Copy the code

Scope slot

Application scenario: A parent component works on a child component

Example:

Controls child component content styles

html:

<div id='app'>
    <fruit-list :list='list'>
        <template slot-scope='slotProps'>
            <strong v-if='slotProps.finfo.id === 1' class='current'>
                {{slotProps.finfo.name}}
            </strong>
            <span v-else>{{slotProps.finfo.name}}</span>
        </template>
    </fruit-list>
</div>
Copy the code

js:

Vue.component('fruit-list', {
    props: ['list'].template: ` 
      
  • {{item.name}}
  • `
    ,})var vm = new Vue({ el: '#app'.data: { list: [{id: 0.name: 'apple' }, { id: 1.name: 'banana' }, { id: 2.name: 'chanche'},]}})Copy the code