Is there a way to pass additional data to event handlers when using the object structure syntax?
Example:
MySFC.vue:
<template>
<template v-for="action in actions" : key="action.id">
<button v-on="action.eventHandlers"> <!--Looking for some way to pass both event and additional data here-->
{{ action.name }}
</button>
</template>
</template>
<script>
import { actions } from '@/lib/my-actions.js';
export default {
setup(props, ctx){
return{
actions,
}
},
}
</script>
my-actions.js:
export const actions = {
name: 'my action',
eventHandlers: {
click: (event, myData) => {
console.log(myData);
},
mousedown: (event, myData) => {
console.log(myData);
}
}
}
Normally if you have a specific event you are trying to handle you can just do something like:
<button @click="myClickHandler($event, myData)"> </button>
But in this case I am trying to build a wrapper of sorts for plugins and do not know what events may need to be handled, so I can't pre-define with v-on which events to look for.
I saw some options for attaching dynamic events, but I only see examples where the event itself is passed, not with additional parameters.
You could use Function.prototype.bind() to bind the function's initial arguments. This can only be done with regular functions (not arrow functions).
// @/lib/my-actions.js
const myClickData = {
id: 'my click data',
}
const myMouseDownData = {
id: 'my mousedown data',
}
export const actions = [
{
name: 'my action',
eventHandlers: {
click: function (myData, event) {
console.log('click', { event, myData })
}.bind(undefined, myClickData),
mousedown: function (myData, event) {
console.log('mousedown', { event, myData })
}.bind(undefined, myMouseDownData),
},
},
]