Search code examples
vue-componentvuejs3vue-composition-apivue-slot

Why the context.slots in the Vue setup() function has an empty object?


Accordingly to this Issue it should work with the current version v3.2.x.

But it doesn't.

Here is the playground:

const { createApp } = Vue;

const myComponent = {
  template: '#my-component',
  setup(props, { slots }) {
    console.log(slots)
  }
}

const App = {
  components: { 
    myComponent
  }
}

const app = createApp(App)
app.mount('#app')
<div id="app">  
  <my-component>Default
  <template #footer>Footer</template>
  </my-component>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script type="text/x-template" id="my-component">
<div>
  <slot></slot>
  <hr/>
  <slot name="footer"></slot>
</div>
</script>


Solution

  • The solution was provided by Duannx.

    With console.log(slots) they are listed correctly.

    {
      "footer": (...n)=>{o._d&&Tr(-1);const r=hn(t);let s;try{s=e(...n)}finally{hn(r),o._d&&Tr(1)}return s},
      "default": (...n)=>{o._d&&Tr(-1);const r=hn(t);let s;try{s=e(...n)}finally{hn(r),o._d&&Tr(1)}return s}
    }
    

    Explanation

    JSON.stringify doesn't show the slots since they are functions. Here is the explanation from the MDN Docs JSON.stringify():

    undefined, Function, and Symbol values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to null (when found in an array). JSON.stringify() can return undefined when passing in "pure" values like JSON.stringify(() => {}) or JSON.stringify(undefined).

    Example

    console.log("JSON.stringify(() => {}): " + JSON.stringify(() => {}));
    
    console.log(JSON.stringify({ "func": function () {}, "lmbd": () => {} }))