首页 > 解决方案 > 如何在 v-for 和 v-on:click 中同时获取索引和事件?

问题描述

这是一个简单的 vue 演示:

<body>
<div id="app">
    <ul>
        <li v-for="text,i in todoList" v-on:click="method_1(i)" >{{text}}</li>
    </ul>
    <ul>
        <li v-for="text,i in todoList" v-on:click="method_2" >{{text}}</li>
    </ul>
    <ul>
    </ul>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
<script>
    new Vue({
        el:"#app",
        data:{
            todoList:["aaaaa",'bbbbbb','ccccc']
        },
        methods:{
            method_1:function(i){
                console.log(i) // i is index of v-for
            },
            method_2:function(e){
                console.log(e)
            },
        }
    })

</script>
</body>

我想绑定 onclick 函数并将eventandindex from v-for作为这个函数的参数。

如果我使用v-on:click="method_1(i)"

-- vue 将这个取i之前的变量;

eles 如果我使用v-on:click="method_1

-- vue 会自动click event作为参数。

但是我想要click event之前的变量和变量作为我函数的参数。我该怎么做?

标签: vue.js

解决方案


To use both events and params, you need to have something like example($event, params)

Using your example,

<li v-for="(text, i) in todoList" v-on:click="method_1($event, i)">
  {{ text }}
</li>

methods: {
  method_1: function(ev, i){
    console.log(ev) // this is the event
    console.log(i) // i is index of v-for
  }
}

推荐阅读