'How do I pass v-on/v-bind to component
I am working with Vuetify menu and button components. I am trying to pass the menu and attrs from the activator slot in the template in SomeFile.vue into the v-btn in the MyCustomButtonTemplate.vue file, but I cannot figure out how to do it. Does anyone know how to correctly pass those values? A bare bones example is shown below
SomeFile.vue
<v-menu offset-y>
<template v-slot:activator="{ on: menu, attrs }">
<MyCustomButtonTemplate v-on="menu" v-bind="attrs">
</template>
<v-list>
<v-list-item>
<v-list-item-title>Some Title</v-list-item-title>
</v-list-item>
</v-list>
</v-menu>
MyCustomButtonTemplate.vue
<template>
<v-tooltip top>
<template #activator="{ on: tooltip }">
<v-btn v-on="{...tooltip, ...menu}" v-bind="attrs">Blah</v-btn>
</template>
<span>Some tooltip</span>
</v-tooltip>
</template>
Solution 1:[1]
You can access component event listeners and attributes in $listeners and $attrs objects. Also you can pass them to children with additional event handlers and listeners by destructuring them.
<v-tooltip top>
<template v-slot:activator="{ on }">
<v-btn v-on="{ ...on, ...$listeners }" v-bind="$attrs">Blah</v-btn>
</template>
<span>Some tooltip</span>
</v-tooltip>
Here is the working codesandbox
Solution 2:[2]
First of all you need to make inheritAttrs to false in custom component, because by default vue for bindings will apply to the root element of the child component as normal HTML attributes.
<script>
export default {
inheritAttrs: false,
}
</script>
then you can apply attributes and listeners on your element in custom component.
<template>
<v-tooltip top>
<template #activator="{ on: tooltip }">
<v-btn v-on="{ ...tooltip, ...$listeners }" v-bind="$attrs">Blah</v-btn>
</template>
<span>Some tooltip</span>
</v-tooltip>
</template>
BTW you didnt define menu and attrs as props but you used it like you have it in your component. Most of reserved methods and properties that we use in vue starts with $. Of course this is true only for Options API.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Igor Moraru |
| Solution 2 |
