简体   繁体   English

如何在Vue js中将模板变量传递给事件处理程序方法

[英]How to pass a template variable to event handler method in Vue js

This code: 这段代码:

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

is working well in Vue js. 在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? 那么,如何将环境变量诸如contact.index传递给事件方法呢?

<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. v-on指令会将字符串作为表达式求值。 You don't have to insert extra {{ }} . 您不必插入额外的{{ }}

Adding to Leo's answer, if you are looking for getting index of v-for loop than you have to do following: 添加到Leo的答案中,如果您要获取v-for循环的索引,则必须执行以下操作:

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

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. 因为您要在v-on:click指令中使用模板部分{{}} ,而VueJS将该模板部分称为普通JS,所以在这里{{}}不能接受模板-胡须。

Previous answers give you correct and working solutions. 先前的答案为您提供了正确且可行的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM