0

This code:

<tbody v-for="contact in contacts">
    <tr v-on:click="selectContact(1)">

is working well in Vue js.

But this:

<tbody v-for="contact in contacts">
    <tr v-on:click="selectContact({{contact.index}})">

Doesn't seem to work well. Resulting in an error. So how can I pass a environmental variable like contact.index into the event method?

3 Answers 3

2
<tbody v-for="contact in contacts">
    <tr v-on:click="selectContact(contact.index)">

or simply

<tbody v-for="contact in contacts">
    <tr @click="selectContact(contact.index)">

v-on directive will evaluate the string as an expression. You don't have to insert extra {{ }}.

Sign up to request clarification or add additional context in comments.

Comments

1

Adding to Leo's answer, if you are looking for getting index of v-for loop than you have to do following:

<tbody v-for="(contact, index) in contacts">
    <tr v-on:click="selectContact(index)">

1 Comment

Absolutely. Check out example 2 in the doc vuejs.org/v2/guide/list.html#Basic-Usage
1

Second code resulting error that is related to interpolation

<tbody v-for="contact in contacts">
    <tr v-on:click="selectContact({{contact.index}})">

Why this happening ? Because you are using templating part {{}} into v-on:click directive, which VueJS see as normal aka vanilla JS, so it can't accept the templating here {{}} - mustaches.

Previous answers give you correct and working solutions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.