当前位置:首页 > VUE

vue点击实现多选

2026-03-09 07:21:19VUE

实现多选的基本思路

在Vue中实现多选功能通常需要维护一个数组来存储选中的项,通过点击事件动态添加或移除元素。以下是两种常见场景的实现方法。

基于列表的多选实现

创建一个数组存储选中项的ID或对象,通过v-for渲染列表,利用v-model或点击事件切换选中状态。

<template>
  <div>
    <div 
      v-for="item in items" 
      :key="item.id"
      @click="toggleSelection(item)"
      :class="{ 'selected': selectedItems.includes(item.id) }"
    >
      {{ item.name }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: '选项1' },
        { id: 2, name: '选项2' },
        { id: 3, name: '选项3' }
      ],
      selectedItems: []
    }
  },
  methods: {
    toggleSelection(item) {
      const index = this.selectedItems.indexOf(item.id);
      if (index === -1) {
        this.selectedItems.push(item.id);
      } else {
        this.selectedItems.splice(index, 1);
      }
    }
  }
}
</script>

<style>
.selected {
  background-color: #42b983;
  color: white;
}
</style>

使用复选框组实现多选

通过v-model直接绑定到数组,适合表单提交场景。

<template>
  <div>
    <div v-for="item in items" :key="item.id">
      <input 
        type="checkbox" 
        :id="'checkbox-' + item.id" 
        :value="item.id" 
        v-model="selectedItems"
      >
      <label :for="'checkbox-' + item.id">{{ item.name }}</label>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: '选项1' },
        { id: 2, name: '选项2' },
        { id: 3, name: '选项3' }
      ],
      selectedItems: []
    }
  }
}
</script>

对象数组的完整选择处理

当需要存储整个对象而非ID时,可使用findIndex进行比较。

methods: {
  toggleSelection(item) {
    const index = this.selectedItems.findIndex(
      selected => selected.id === item.id
    );
    if (index === -1) {
      this.selectedItems.push(item);
    } else {
      this.selectedItems.splice(index, 1);
    }
  }
}

性能优化建议

对于大型列表,使用Set或对象哈希来提升查找效率。

vue点击实现多选

data() {
  return {
    selectedSet: new Set()
  }
},
methods: {
  toggleSelection(id) {
    if (this.selectedSet.has(id)) {
      this.selectedSet.delete(id);
    } else {
      this.selectedSet.add(id);
    }
  }
}

注意事项

  • 确保为循环项设置唯一的:key
  • 复杂对象建议使用深拷贝避免引用问题
  • 移动端可添加@touchstart事件增强交互体验

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

相关文章

vue伪函数实现

vue伪函数实现

Vue 伪函数实现方法 伪函数(Mock Function)在 Vue 中常用于测试或模拟某些逻辑,以下是几种常见的实现方式: 使用 Jest 的 jest.fn() 在单元测试中,可以通过 Jes…

vue实现计时

vue实现计时

Vue 实现计时功能 在 Vue 中实现计时功能可以通过多种方式完成,以下是几种常见的方法: 使用 setInterval 实现基础计时器 通过 setInterval 和 clearInterva…

vue实现弹窗

vue实现弹窗

Vue 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

eventbus vue实现

eventbus vue实现

EventBus 实现原理 EventBus 是一种发布/订阅模式,用于 Vue 组件间的通信。核心是通过一个中央事件总线管理事件监听和触发。 创建 EventBus 在 Vue 项目中创建一个独立…

vue实现登出

vue实现登出

实现Vue登出功能 登出功能通常涉及清除用户会话、令牌或本地存储的数据,并重定向到登录页面。以下是几种常见的实现方式: 清除用户令牌和状态 在Vuex的store中定义一个logout mutati…

vue实现视频

vue实现视频

Vue 实现视频播放的方法 在 Vue 项目中实现视频播放可以通过多种方式完成,以下是几种常见的方法: 使用 HTML5 的 <video> 标签 在 Vue 组件中直接使用 HTML…