SoFunction
Updated on 2025-04-04

Detailed explanation of slot instance in the component

slot in Vue component

slot can add content to already defined components, and the components will receive content and output. If there is a component person, it contains personal information, as shown below

 <template >
    <div>
      <p>Name:...</p>
      <p>age:...</p>
      <p>Profession:...</p>
    </div>
  </template>

When applying, of course I hope this can be flexible and varied, so this requires slot.

The first thing to do is to create such a component. Here I am using the form of <template>, as shown below

&lt;template &gt;
    &lt;div&gt;
      &lt;p&gt;Name:&lt;/p&gt;
      &lt;p&gt;age:&lt;/p&gt;
      &lt;p&gt;Profession:&lt;/p&gt;
    &lt;/div&gt;
  &lt;/template&gt;

You can see that I have added an id to the template here, this is for the following operations

Next, use Vue's constructor, create a Vue instance, and then add local components, as shown below

  var person = {
     template : "#per" //Use id    };
    new Vue({
      el: "#app",
      data: {
        componentData: {
          name : "vam",
          age : 18,
          job : "student"
        }
      },
      components : {
        "person" : person
      }
    });

Next, add something when using the <person> component, which is the specific content, as follows:

  <div >
    <person>
      <span slot="name">{{}}</span>
      <span slot="age">{{}}</span>
      <span slot="job">{{}}</span>
    </person>
  </div>

Of course, this is not enough. You have to have something in the template. As follows, slot should be used here.

 &lt;template &gt;
    &lt;div&gt;
      &lt;p&gt;Name:&lt;slot name="name"&gt;&lt;/slot&gt;&lt;/p&gt;
      &lt;p&gt;age:&lt;slot name="age"&gt;&lt;/slot&gt;&lt;/p&gt;
      &lt;p&gt;Profession:&lt;slot name="job"&gt;&lt;/slot&gt;&lt;/p&gt;
    &lt;/div&gt;
  &lt;/template&gt;

Then you can see the desired result

The above is an explanation of the slot instance in the middle component. If you have any questions, please leave a message to discuss and make progress together. Thank you for reading. I hope it can help you. Thank you for your support for this site!