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

安稳与你 提交于 2019-11-27 03:35:25

问题


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 ?


回答1:


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




回答2:


@click="[fuctionName]($event, index)"

Example:

<button v-for="(button,index) in items" @click="[fuctionNames[index]]($event, index)" > // consider fuctionNames array of Function Names.



回答3:


You can pass data with event

or, take a readonly input field with v-model

Example :

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

</tr>  

new Vue({
  ...
  ...
  methods:{
    itemClick:function(event){
       console.log(event.target.value);
    }
  }
})


来源:https://stackoverflow.com/questions/52811581/how-to-pass-a-dynamic-function-name-to-the-click-event-in-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!