javascriptvue.jsvuejs2vuetify.jsv-slot

Vue, composition: pass a "slot" prop as a an attribute value


In React is very easy, since there's no "slots". Everything are parameters. But I don't know how to pass a slot as a parameter. Here's what I did.

I created a new component, which uses the v-menu component from Vuetify:

// SelectorComponent.vue
<template>
  <v-menu>
    <template v-slot:activator="{ on }">
      <slot name="activator" v-on="on" />
    </template>
    ...

Then I used that component:

<Selector>
  <template v-slot:activator="{ on }">
    <v-btn text v-on="on">Type</v-btn>
  </template>
</Selector>

And when you presses the "Type" button, it doesn't show the menu. However, if I replace the slot by the button, it works:

// It works!
<template>
  <v-menu outlined :close-on-content-click="false" offset-y>
    <template v-slot:activator="{ on, attrs }">
      <v-btn text v-on="on">Type</v-btn>
    </template>

what am I doing wrong?


Solution

  • You should use scoped slots by naming the slot activator and binding on attribute to on slot prop which could be drilled down to your custom component, inside it you receive that on as <template v-slot:activator="{ on }"> :

    / SelectorComponent.vue
    <template>
      <v-menu>
        <template v-slot:activator="{ on }">
          <slot name="activator" :on="on" />
        </template>
        ...
    

    then use it like :

    <Selector>
      <template v-slot:activator="{ on }">
        <v-btn text v-on="on">Type</v-btn>
      </template>
    </Selector>