Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a dynamic function name to the click event in Vue Js

Is there any way we can pass the function name from the parameters ?

some thing like this..

<tr v-for="item in items" class="static" 
    v-bind:class="{'evenRow': item.oddeven=='1', 'oddRow': item.oddeven=='0' }"
@click="item.click(item.contactID)" >

</tr>  

item.click is not converting as corresponding function while rendering the page. what is the correct approach any suggestions will be appreciated ?

like image 822
Tony Tom Avatar asked Oct 15 '18 07:10

Tony Tom


People also ask

How do I create a dynamic reference in Vue?

Simply use v-bind like :ref="'element' + result.id" or ref="`element${result.id}`" .

How do you pass event objects in Vue?

To pass event and argument to v-on in Vue. js, we can call the event handler method with $event and whatever argument. And then we can retrieve the arguments from the method parameters in the same order. to call addToCart with the $event object and the ticket.id property.

What is dynamic component in VUE JS?

js Dynamic Components allows the users to switch over the components without updating the route of the Vue. js application itself. It also keeps the data in its current state. It is useful when the user is in a tabbed interface.

What is modifier in VUE JS?

The following modifiers are available in Vue. stop - Prevents event bubbling up the DOM tree. prevent - Prevents default behavior. capture - Capture mode is used for event handling. self - Only trigger if the target of the event is itself.


1 Answers

To use dynamic function call it is suggested to have a helper function that receives the function name and call the corresponding function.

handle_function_call(function_name) {
    this[function_name]()
},

And from template when iterating over items you can call that function by passing the function name like

<button v-for="button of items"
       :key="button.id" 
       @click="handle_function_call(button.fn_name)" //=> note here
>
  {{ button.text }}
</button>

See it in action in jsfiddle

like image 96
Roland Avatar answered Sep 22 '22 22:09

Roland