[vue2] Introduction, classification and use of slots

I. Introduction

The use frequency of slots in development is not low, and the use of slots can help us better personalize development.

2. Classification

1. Default slot

Just define <slot></slot> in the subcomponent

2. Named slot

Define <slot name="xxx"></slot> in the subcomponent, where xxx is the name of the slot

3. Scope slots

Define <slot: aaa="xxx"></slot> in the subcomponent, where aaa is the dynamic attribute name and xxx is the data name in data

3. Case

1. Default slot

Child component: the content in the slot, displayed when the parent component does not pass the content

<template>
  <div>
    <slot>没有内容时我显示</slot>
  </div>
</template>

Parent component: <demo/> is the defined child component name

<demo>
   <h2>默认插槽</h2>
</demo>

2. Named slot

Subassembly:

<div>
    <slot name="one">没有内容时我显示</slot>
    <slot name="two">没有内容时我显示</slot>
</div>

parent component:

<demo>
   <h2 slot="one">我在使用具名插槽1</h2>
   <h2 slot="two">我在使用具名插槽2</h2>
</demo>

3. Scope slots

Subcomponent: pass parameters to the parent component, :msg binds dynamic properties, and the data name in data follows the equal sign

<template>
  <div>
    <slot :msg="msg">没有内容时我显示</slot>
  </div>
</template>

Parent component: Use slot-scope to receive the parameters of the child component, where the name after the equal sign can be defined freely. However, due to the parameter format, you need to use dots when using it to get the real data

<demo>
   <h2 slot-scope="content">{
   
   {content.msg}}</h2>
</demo>

When you don’t need to click, use content directly, and the page is displayed as follows

4. Pay attention

① When the default slot is used, the page will be displayed several times when the parent component is called several times

<demo>
  <h2>默认插槽1</h2>
</demo>
<demo>
  <h2>默认插槽2</h2>
</demo>

②When using a named slot, if the parent component does not specify the slot name of the child component, the content of the parent component will not be displayed correctly. It will think that you do not use the slot, and will display the specific content in the slot of the child component.

4. Others

The above is all the introduction of the slot, let's make progress together.

Guess you like

Origin blog.csdn.net/weixin_44431073/article/details/125081627