Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js handle multiple click event

I have a list and want to handle a click event for each item in the list

<ul>
  <li 
    v-for="item, index in items" 
    :key="index"
    @click="select(item)"
  >
    {{ item }}
  </li>
</ul>

And the script is

...
methods: {
  select(item) {
    console.log('Select', item)
  }
}

This works well when there are about 10 items. However, when there are about 1000 items, the performance becomes very slow because I attach 1000 events for 1000 items.

The solution is to attach only one click event for the list and use event.target

<ul @click="select($event)">
  <li 
    v-for="item, index in items" 
    :key="index"
  >
    {{ item }}
  </li>
</ul>

In function select, how can I get item corresponding to each item?

like image 367
pexea12 Avatar asked Mar 07 '17 10:03

pexea12


1 Answers

You can use

<ul @click="select($event)">
  <li 
    v-for="item, index in items" 
    :key="index"
    :id="index"
  >
    {{ item }}
  </li>
</ul>

Then in your select:

select($event) {
  console.log('Select ', $event.srcElement.id)
}
like image 90
Quoc-Anh Nguyen Avatar answered Sep 17 '22 07:09

Quoc-Anh Nguyen