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?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With