Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get both index and event in v-for and v-on:click?

Tags:

vue.js

This is a simple vue demo:

<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>

I want to bind onclick function and put event and index from v-for as this function's params.

If I use v-on:click="method_1(i)":

-- vue will this take i is varibale of before;

eles if I use v-on:click="method_1 :

-- vue will automatlly take click event as params.

But I want both click event and variable of before as my function's params.How can I do that?

like image 906
bytefish Avatar asked May 05 '18 10:05

bytefish


1 Answers

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
  }
}
like image 65
Ru Chern Chong Avatar answered Nov 20 '22 02:11

Ru Chern Chong