3👍
Event handling in Vue
When the value of the v-on
directive (@
for shorthand) is a function name, the template compiler converts it into a function call that includes the event argument.
For example, this markup:
<CustomButton @submit="upload">Submit</CustomButton>
…is equivalent to:
<CustomButton @submit="(e) => upload(e)">Submit</CustomButton>
The event argument (e
) is the data the CustomButton
passed when emitting the submit
event. Assume CustomButton
‘s doSomething()
is called here:
// CustomButton.vue
export default {
methods: {
doSomething() {
const eventData = { name: 'product 1', quantity: 100 }
this.$emit('submit', eventData)
}
}
}
Notice the type of event argument is:
{
name: string,
quantity: number,
}
Given the @submit
handling setup above, the parent would recieve the submit
event, and call upload()
with that event argument:
// Parent.vue
export default {
methods: {
upload(eventData) {
console.log({ name: eventData.name, quantity: eventData.quantity })
}
}
}
With object destructuring in the argument list, that code can be rewritten as this:
// Parent.vue
export default {
methods: {
upload({ name, quantity }) {
console.log({ name, quantity })
}
}
}
And that’s the pattern you’re seeing in the sample code.
Events
The Vuetify API docs for each component list all events and their arguments (v-calendar
‘s API / events).
Given the event arguments below, it makes sense to see the following method signatures…
@mousedown:event="startDrag"
Event argument for mousedown:event
:
{
event: any,
⋮
timed: boolean,
⋮
}
Method signature:
export default {
methods: {
startDrag({ event, timed }) {⋯}
}
}
@click:event="showEvent"
Event argument for click:event
:
{
event: any,
⋮
nativeEvent: MouseEvent | TouchEvent
}
Method signature:
export default {
methods: {
showEvent({ event, nativeEvent }) {⋯}
}
}
@change="updateRange"
Event argument for change
:
{
start: {⋯},
end: {⋯}
}
Method signature:
export default {
methods: {
updateRange({ start, end }) {⋯}
}
}