John Moore
John Moore

Reputation: 7129

Issue with functions as props for components

I have a type of button I use throughout my application, an example of which is this: <button type="button" class="btn btn-default" @click.prevent="search">Search</button>. Although the savings in code characters are small, it struck me as worthwhile to create a little component for this, Btn. I could use this thus: <btn :action="search">Search</btn>. All well and good.

But I have a problem when I want to use one of Vue's internal special variables as an argument in the function. For example, <btn :action="removeSelected(index,$event)">X</btn>. The 'removeSelected' function needs to be passed the event as the second parameter. It's not valid as an argument in the function passed as a prop in a component, though. I get the error message: "[Vue warn]: Property or method "$event" is not defined on the instance but referenced during render." Is there any way round this?

Upvotes: 1

Views: 223

Answers (1)

Bert
Bert

Reputation: 82489

The main issue here is that you want to pass a function to the child component that will receive the $event parameter (which all event handlers receive by default) as well as passing a parameter defined in the parent. In order to do that, you can define a function inside the action parameter itself.

:action="($event) => removeSelected(index, $event)"

This defines a function that receives $event as a parameter that calles the removeSelected method with the capture index and passes along the event.

Working example.

Upvotes: 1

Related Questions