vue实现列表点击
Vue 实现列表点击的方法
在 Vue 中实现列表点击功能通常涉及 v-for 渲染列表和 v-on(或 @)绑定点击事件。以下是几种常见实现方式:
基础列表点击
使用 v-for 渲染列表,并通过 @click 绑定点击事件:
<template>
<ul>
<li
v-for="(item, index) in items"
:key="index"
@click="handleClick(item)"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
}
},
methods: {
handleClick(item) {
console.log('Clicked:', item)
}
}
}
</script>
高亮当前选中项
通过动态类名或样式实现选中状态:
<template>
<ul>
<li
v-for="item in items"
:key="item.id"
@click="selectedItem = item"
:class="{ 'active': selectedItem === item }"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
selectedItem: null,
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
}
}
}
</script>
<style>
.active {
background-color: #f0f0f0;
}
</style>
传递额外参数
若需要同时传递索引或其他参数:

<template>
<ul>
<li
v-for="(item, index) in items"
:key="index"
@click="handleClick(item, index, $event)"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
methods: {
handleClick(item, index, event) {
console.log('Item:', item, 'Index:', index, 'Event:', event)
}
}
}
</script>
使用事件修饰符
Vue 提供的事件修饰符可简化事件处理:
<template>
<ul>
<li
v-for="item in items"
:key="item.id"
@click.stop="handleClick(item)"
>
{{ item.name }}
</li>
</ul>
</template>
常用修饰符:

.stop:阻止事件冒泡.prevent:阻止默认行为.once:只触发一次
性能优化
对于长列表,建议使用 v-once 或虚拟滚动:
<li
v-for="item in items"
:key="item.id"
v-once
@click="handleClick(item)"
>
{{ item.name }}
</li>
组件化列表项
将列表项封装为组件实现复用:
<template>
<ul>
<list-item
v-for="item in items"
:key="item.id"
:item="item"
@item-click="handleClick"
/>
</ul>
</template>
<script>
import ListItem from './ListItem.vue'
export default {
components: { ListItem },
methods: {
handleClick(item) {
console.log('Parent received:', item)
}
}
}
</script>
ListItem.vue 组件:
<template>
<li @click="$emit('item-click', item)">
{{ item.name }}
</li>
</template>
<script>
export default {
props: ['item']
}
</script>






