Adding Extra Parameters to Vue.js Event Handlers

— 4 minute read


We all know how to add a listener to an event coming out of a Vue.js component, right?

<my-toolbar @action-clicked="onActionClicked" />

Dead easy.

This will execute the onActionClicked method when the action-clicked event is emitted from the my-toolbar component. The onActionClicked method will receive the parameters passed from the $emit call within the component. For example, the $emit function might pass up the toolbar item that was clicked - this.$emit(item). Our onActionClicked method signature would then be like this.

onActionClicked(toolbarItem) {
this.showLoadingScreen = true;

switch(toolbarItem.id) {
case 'save':
...
break;
case 'load':
...
break;
}

this.showLoadingScreen = false;
}

Our handler method flips a toggle that shows a load mask of some sort, and then figures out what action to do based on the toolbar item's id.

So. Nothing too much new there.

However, perhaps we want introduce another my-toolbar instance, which has the same action items (and therefore the same handler should be used) but we don't want these actions to show a load mask.

First we can modify the handler function to allow the load mask to be shown conditionally:

onActionClicked(showLoadingScreen, toolbarItem) {
if (showLoadingScreen) {
this.showLoadingScreen = true;
}

switch(toolbarItem.id) {
case 'save':
...
break;
case 'load':
...
break;
}

this.showLoadingScreen = false;
}

The problem now is that with the new showLoadingScreen parameter added, it will be populated with the toolbar item's object, with toolbarItem being left undefined.

To get around this we change our handler where it is bound to the event, so it populates this parameter with the right value. It might look like this will bind the result of the onActionClicked(true) to the event handler, but it actually uses this as the execution code.

<!-- first toolbar - show load mask -->
<my-toolbar @action-clicked="onActionClicked(true)" />

<!-- second toolbar - don't show load mask -->
<my-toolbar @action-clicked="onActionClicked(false)" />

With this code our showLoadingScreen parameter will be populated with our boolean - perfect. However, our toolbarItem parameter will still be undefined, because by defining our own list of parameters it nukes the default set.

To fix this we must append all the default parameters we receive (i.e. the ones received from the event directly) using the arguments constant and the "spread" operator - ....

<!-- first toolbar - show load mask -->
<my-toolbar @action-clicked="onActionClicked(true, ...arguments)" />

<!-- second toolbar - don't show load mask -->
<my-toolbar @action-clicked="onActionClicked(false, ...arguments)" />

And that's all there is to it. You can use this technique to change the parameters sent to an event handler any way you want.

Filed under