当前位置:首页 > VUE

vue实现li多选

2026-03-08 12:21:27VUE

实现思路

在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)查找)比数组更高效:

vue实现li多选

data() {
  return {
    selectedMap: {}
  }
},
methods: {
  toggleSelect(id) {
    this.$set(this.selectedMap, id, !this.selectedMap[id])
  }
}

注意事项

  • 使用v-for时必须添加:key
  • 选中状态样式应明确区分未选中状态
  • 移动端建议增加点击区域大小
  • 复杂场景可考虑使用Vuex管理状态

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

相关文章

vue实现3d宇宙

vue实现3d宇宙

Vue实现3D宇宙效果 使用Three.js库 Three.js是一个强大的JavaScript 3D库,可以轻松集成到Vue项目中。安装Three.js依赖: npm install three…

vue alert实现

vue alert实现

使用 Vue 实现 Alert 组件 在 Vue 中实现 Alert 组件可以通过自定义组件或结合第三方库完成。以下是几种常见方法: 自定义 Alert 组件 创建一个可复用的 Alert 组件,通…

vue实现标题

vue实现标题

Vue 实现标题的方法 在Vue中实现标题可以通过多种方式,以下是几种常见的方法: 方法一:使用模板语法 在Vue组件的模板中直接使用HTML的<h1>到<h6>标签来定义…

vue单选实现

vue单选实现

Vue 单选实现 在 Vue 中实现单选功能可以通过多种方式完成,以下是几种常见的方法: 使用 v-model 绑定单选按钮 通过 v-model 绑定一个变量,可以实现单选效果。当用户选择不同的选…

vue实现甘特图

vue实现甘特图

使用 Vue 实现甘特图 基于开源库(如 vue-ganttastic) 安装依赖库: npm install vue-ganttastic 示例代码: <template> &l…

vue 实现原理

vue 实现原理

Vue 实现原理 Vue.js 是一个渐进式 JavaScript 框架,其核心实现原理主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是 Vue 实现原理的核心要点: 响应式系统 Vu…