vue实现li多选
实现思路
在Vue中实现<li>多选功能,可以通过v-model绑定选中状态数组,结合v-for渲染列表项,并监听点击事件来更新选中状态。

基础实现代码示例
<template>
<ul>
<li
v-for="(item, index) in items"
:key="index"
@click="toggleSelect(index)"
:class="{ 'selected': selectedIndices.includes(index) }"
>
{{ item.text }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ text: '选项1' },
{ text: '选项2' },
{ text: '选项3' }
],
selectedIndices: []
}
},
methods: {
toggleSelect(index) {
const idx = this.selectedIndices.indexOf(index)
if (idx === -1) {
this.selectedIndices.push(index)
} else {
this.selectedIndices.splice(idx, 1)
}
}
}
}
</script>
<style>
.selected {
background-color: #eee;
}
</style>
对象数组的选中处理
若需选中整个对象而非索引,可修改为:

data() {
return {
items: [
{ id: 1, text: '选项1' },
{ id: 2, text: '选项2' },
{ id: 3, text: '选项3' }
],
selectedItems: []
}
},
methods: {
toggleSelect(item) {
const idx = this.selectedItems.findIndex(i => i.id === item.id)
if (idx === -1) {
this.selectedItems.push(item)
} else {
this.selectedItems.splice(idx, 1)
}
}
}
使用复选框的实现方式
更符合无障碍访问规范的实现:
<template>
<ul>
<li v-for="item in items" :key="item.id">
<label>
<input
type="checkbox"
v-model="selectedItems"
:value="item"
>
{{ item.text }}
</label>
</li>
</ul>
</template>
性能优化建议
对于大型列表,使用对象存储选中状态(O(1)查找)比数组更高效:
data() {
return {
selectedMap: {}
}
},
methods: {
toggleSelect(id) {
this.$set(this.selectedMap, id, !this.selectedMap[id])
}
}
注意事项
- 使用
v-for时必须添加:key - 选中状态样式应明确区分未选中状态
- 移动端建议增加点击区域大小
- 复杂场景可考虑使用Vuex管理状态






