ChatGPT解决这个技术问题 Extra ChatGPT

How to pass a parameter to Vue @click event handler

I am creating a table using Vue.js and I want to define an onClick event for each row that passes contactID. Here is the code:

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

On clicking a row, it is calling addToCount(), which is working. I want to pass item.contactID to addToCount(). Could someone suggest the correct syntax for this?


L
Linus Borg

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

Nice!! Just what I needed to know
the event object saved the day~
A
Alexander Kim

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"


What if the argument I want to pass is not iterated through and keyable but rather hard coded as such <a href="#" @click="switchRoom" class="rooms">Interview Room</a> <a href="#" @click="switchRoom" class="rooms">Green Room</a> <a href="#" @click="switchRoom" class="rooms">Bavarian Caviar Room</a> <a href="#" @click="switchRoom" class="rooms">Sky Room</a> and I wanted to use the text content of the a elements in the switchRoom method?
@AkinHwan If it's already hard coded, just send the text as a parameter @click="switchRoom('Sky Room')"
What if it is not owned by the vue instance. For example you want to over-ride a chart click through and the chart sits in a vue directive but is not itself vue. You need to call the underlying click event somehow from the override vue click function?
f
fotiecodes

I had the same issue and here is how I manage to pass through:

In your case you have addToCount() which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"

in your function implementation you can receive the params like:

addToCount(paramContactID){
 // the paramContactID contains the value you passed into the function when you called it
 // you can do what you want to do with the paramContactID in here!

}

Thanks. Your answer is similar to that already provided by @Linus