Home > Net >  Using the Vue "v-slot" feature for a named slot in a javascript object
Using the Vue "v-slot" feature for a named slot in a javascript object

Time:09-15

I come here because I can't find how to use "v-slot" when using the syntax leveraging a javascript object. This syntax I am talking about is the one presented in the course course Syntax handling javascript object

I have a first file named ComponentToBeCalled.js, containing the following code for building a vue component:

app.component('component-to-be-called', {
            data: function(){},
            props: {},
              template:
              /*html*/
              `<div>
                   SOME_HTML_HERE
               </div>`,
              computed: {},
              methods: {}
            })

I have a second file named ParentComponent.js with the following code for building another vue component:

app.component('parent-component', {
    data: function(){},
    props: {},
      template:
      /*html*/
      `<div>
           <slot name="SLOT_NAME"></slot>
       </div>`,
      computed: {},
      methods: {}
    })

--> My objective would be to build 'component-to-be-called' within 'parent-component'. From what I read, the classic syntax for defining a named slot in a CompenentToBeCalled.vue file would be:

<component-to-be-called>
  <template v-slot:SLOT_NAME>
    <div>
         SOME_HTML_HERE
    </div>
  </template>
</component-to-be-called>

Do you know what is the equivalent when we play with a javascript object ?

__

CodePudding user response:

Your first bit of code is defining a regular component (component-to-be-called). Your second bit of code is defining a component which has a slot (parent-component).

If you want to have a component-to-be-called inside a parent-component using the slot, you would do as follows:

<parent-component>
    <template v-slot:SLOT_NAME>
        <component-to-be-called />
    </template>
</parent-component>

This would render as:

<div>   //This is from parent-component
    <div>   //This is from component-to-be-called
        SOME_HTML_HERE
    </div>
</div>

The official docs has some nice diagrams to help you get your head around what goes where. Be careful though that what the docs calls parent template is the template that's using the Component with the defined slot.

This should all work the same with plain javascript syntax (template: "<div>...) or Single File Components.

  • Related