Basic use of slot in vue component

1. Concept

slot Translate to slots

Why use slot?

  • The slot of the component is to reserve some space for the packaged component, which is more expandable.
  • Once we reserve the slot, we can let users decide what to insert into the slot according to their needs.

2. Basic use of slot

  • The best way to encapsulate is to extract commonalities into components and expose differences as slots.
  • In subassembly using special element <slot>can open a sub-assembly that slot.
  • <slot></slot> The content in indicates that if no other content is inserted in the component, the content will be displayed by default
<div id="app">
  <cpn></cpn>
  <cpn>
    <h3>啦啦啦啦</h3>
  </cpn>
</div>

<template id="cpn">
  <div>
    <h2>我是组件的标题</h2>
    <slot>
      <p>我是组件的默认内容</p>
    </slot>
  </div>
</template>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  let vm = new Vue({
     
     
    el: "#app",
    data: {
     
     },
    components: {
     
     
      cpn: {
     
     
        template: '#cpn'
      }
    }
  });
</script>

Insert picture description here


3. Named Slot

When the function of the subcomponent is complicated, the slot of the subcomponent may not be one.

  • For example, if we encapsulate a sub-component of a navigation bar, three slots may be needed, representing the left, middle, and right sides.
  • So, when the outside is inserting content into the slot, how to distinguish which one is inserted?
  • At this time, we need to give the slot a name

How to use named slots? Very simple, just give a slot element attribute can name <slot name='myslot'></slot>, a name without the <slot>exports will implicitly with the name " default "

vue official website-named slots

Named slot since been updated from 2.6.0, vue official website recommended v-slotinstructions. Official website screenshot:

Insert picture description here

<template id="cpn">
  <div>
    <slot name="header">我是页面默认头部</slot>
    <slot></slot>
    <slot name="footer">我是页面默认底部</slot>
  </div>
</template>

When providing content to a named slot, we can one <template>use the element of v-slotinstruction, and to v-slotprovide the name of the formal parameter:

<div id="app">
  <cpn>
    <template v-slot:header>
      <h1>页面头部标题</h1>
    </template>

    <p>页面中间内容</p>

    <template v-slot:footer>
      <h1>页面底部标题</h1>
    </template>
  </cpn>
</div>

Note that v-slotyou can only add in <template>the (only one exception )

Abbreviation for named slot

2.6.0 New

Like v-on and v-bind, v-slot also has an abbreviation, that is v-slot:, replace all content ( ) before the parameter with characters #. For example, v-slot:headerit can be rewritten as#header


4. Scope slot

vue official website-scope slot

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/112647217