vue实现点击选中列表
实现点击选中列表
在Vue中实现点击选中列表的功能,可以通过v-for指令渲染列表,结合v-bind:class或v-model动态绑定选中状态。以下是两种常见实现方式:
基础实现(单选)
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
@click="selectItem(index)"
:class="{ 'active': selectedIndex === index }"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' }
],
selectedIndex: null
}
},
methods: {
selectItem(index) {
this.selectedIndex = index
}
}
}
</script>
<style>
.active {
background-color: #f0f0f0;
color: #42b983;
}
</style>
多选实现
<template>
<ul>
<li
v-for="(item, index) in list"
:key="index"
@click="toggleSelect(index)"
:class="{ 'active': selectedItems.includes(index) }"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' }
],
selectedItems: []
}
},
methods: {
toggleSelect(index) {
const idx = this.selectedItems.indexOf(index)
if (idx > -1) {
this.selectedItems.splice(idx, 1)
} else {
this.selectedItems.push(index)
}
}
}
}
</script>
使用计算属性优化
对于复杂场景,可以使用计算属性管理选中状态:
<template>
<ul>
<li
v-for="(item, index) in list"
:key="item.id"
@click="selectedId = item.id"
:class="{ 'active': selectedId === item.id }"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
],
selectedId: null
}
}
}
</script>
注意事项
- 使用唯一标识(如
id)作为key比数组索引更可靠 - 选中状态可以存储在Vuex中实现跨组件共享
- 对于大量数据,考虑使用虚拟滚动优化性能
- 移动端可添加
@touchstart事件提升响应速度







