Uniapp 中 Li 悬停获取下标方法
<template>
<ul>
<li v-for="(item, index) in list" :key="item.id" :id="'item_' + index" @mouseover="handleMouseover">{{ item.name }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: 'item1' },
{ id: 2, name: 'item2' },
{ id: 3, name: 'item3' }
]
}
},
methods: {
handleMouseover(event) {
const id = event.currentTarget.id; // 获取当前 li 的 id
const index = Number(id.split('_')[1]); // 解析出当前 li 的索引值
console.log(index);
}
}
}
</script>
<p>在上面的代码中,我们为每个 li 元素绑定了一个唯一的 id,并通过监听 mouseover 事件来获取当前 li 的 id,然后解析出索引值。</p>
原文地址: https://www.cveoy.top/t/topic/lHh5 著作权归作者所有。请勿转载和采集!