How to use slot in vuejs

Keywords: Fragment Vue Attribute

Official website address: https://cn.vuejs.org/v2/guide/render-function.html

Usage scenario of slot: if you want to add a paragraph of html or text inside the defined component, for example

<my-button>

<p>Hello world</p>

</my-button>

In this case, you can use slot to display the inserted html code in the slot position of the template. My button component is defined as follows:

<div id="box">
  <mybutton>
    <p>hello world</p>
  </mybutton>
  <hr>
  <mybutton></mybutton>
</div>
<template id="mybutton">
  <div>
    <button @click="show">
      <slot></slot>
    </button>
  </div>
</template>
</body>
<script>
  new Vue({
    el:'#box',
    components:{
      'mybutton':{
        template:'#mybutton',
        methods:{
          show:()=>{
            alert(1);
          }
        }
      }
    }
  });
</script>

Display:


If slot is used and HTML code is not added to the custom component, the slot location will not be displayed. Of course, you can set

The default value of slot. Change the slot of the above template to

<template id="mybutton">
  <div>
    <button @click="show">
      <slot>I'm the default</slot>
    </button>
  </div>
</template>
The re run result is as follows:

Conclusion: Slot can be understood as a slot. HTML inserted in the use of components can be displayed in the slot location

Named slot

If more than one slot is used in the template, a named slot is required.

The slot tag has an attribute name, which configures the distribution content. Multiple slots can have multiple different names. Named slots will match the elements with slot characteristics of the corresponding segment

Using multiple slot tags, you can also use an anonymous slot as the slot of an unmatched HTML fragment. If there is no anonymous slot, the unmatched HTML fragment will be discarded

<div id="box">
  <my-list>
    <p>My product list</p>
    <ul slot="head">
      <li>Beer</li>
      <li>mixed congee</li>
    </ul>
    <ol slot="footer">
      <li>Apple</li>
      <li>Tomatoes</li>
    </ol>
  </my-list>
  <br>
  <span>
    <p>No HTML fragment</p>
    <my-list></my-list>
  </span>


</div>
<template id="list">
  <div>
   <p>hello world!</p>
    <slot></slot>
    <slot name="head">If no fragment matches to, the field displayed_head</slot>
    <slot name="footer">If no fragment matches to, the field displayed_foot</slot>
  </div>
</template>
</body>
<script>
  new Vue({
    el:'#box',
    components:{
      'my-list':{
        template:'#list',
      }
    }
  });
</script>

Operation result:



In this way, the HTML fragment content with the slot feature will be displayed in the corresponding named slot tag. Of course, the named slot can also be set with the default value


     

Posted by MikeTyler on Thu, 21 May 2020 08:47:31 -0700