当前位置:首页 > VUE

vue实现li多选

2026-03-08 12:21:27VUE

实现思路

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

vue实现li多选

基础实现代码示例

<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>

对象数组的选中处理

若需选中整个对象而非索引,可修改为:

vue实现li多选

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管理状态

标签: 多选vue
分享给朋友:

相关文章

vue实现菜单栏锚点

vue实现菜单栏锚点

实现锚点菜单的基本思路 在Vue中实现菜单栏锚点功能,主要涉及两个方面:创建可跳转的锚点位置,以及菜单项的点击滚动控制。通过监听滚动事件可以高亮当前可见区域的对应菜单项。 创建页面锚点位置 在需要跳…

vue实现图库

vue实现图库

Vue 实现图库的基本方法 使用 Vue 实现图库功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用 Vue 和第三方库(如 Vue Gallery) 安装 vue-gallery 或…

vue实现波形

vue实现波形

实现波形效果的方法 在Vue中实现波形效果可以通过多种方式完成,常见的方法包括使用Canvas绘制、CSS动画或第三方库。以下是几种实现方案: 使用Canvas绘制波形 通过Canvas API动态…

vue 简单实现

vue 简单实现

以下是 Vue 的简单实现示例,涵盖基础模板、数据绑定、方法及生命周期: 基础模板与数据绑定 <div id="app"> <p>{{ message }}</p&…

vue实现treetable

vue实现treetable

Vue实现TreeTable的方法 使用第三方组件库(如Element UI) Element UI的el-table组件支持树形表格展示,通过设置row-key和tree-props属性即可实现。…

vue实现组件

vue实现组件

Vue 组件实现基础 Vue 组件是可复用的 Vue 实例,用于封装 UI 和逻辑。通过 .vue 文件或直接注册组件实现。 单文件组件 (SFC) 示例 <template>…