I am aware that this question has been asked already but I still struggle to understand what does it mean?
<v-dialog
v-model="dialog"
width="500"
>
<template v-slot:activator="{ on, attrs }">
<v-btn
color="red lighten-2"
dark
v-bind="attrs"
v-on="on"
>
Click Me
</v-btn>
</template>
(that is taken from official vuetify documentation https://vuetifyjs.com/en/components/dialogs/#usage , but I suspect there is just a JS thing that I don't understand).
What does {on, attrs}
mean and how they propagate down to v-btn
where they are used in v-on
and v-bind
?
CodePudding user response:
There a few concepts here that need to be explained.
"Scoped slots" (or just "slots" since Vue 3) can pass data to the parent component. Think of the slot as kind of like a function with arguments. In this case the activator
slot of <v-dialog>
is passing an object containing properties on
and attrs
for use inside the slot content template. You should refer to the <v-dialog>
docs to know how this data should be used; in this case <v-dialog>
needs to know when the activator is clicked in order to present the dialog, which is why it exposes on
and attrs
that you need to link to whatever custom button you designate to be the dialog activator.
In a lot of component libraries, it's common for slots to expose on
(event listeners) and attrs
(attributes/props) that the component requires you to set on a component in the template; for this you use v-on
and v-bind
respectively. Refer to the docs to see how these directives can be used in this way to bind multiple attributes at once:
<!-- binding an object of attributes -->
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>
This specific syntax (object destructing):
<template v-slot:activator="{ on, attrs }">
<v-btn v-bind="attrs" v-on="on">
is the same as this:
<template v-slot:activator="scope">
<v-btn v-bind="scope.attrs" v-on="scope.on">
The on
and attrs
properties are just being extracted into separate variables.