当前位置:首页 > VUE

vue实现多选效果

2026-02-18 19:36:53VUE

Vue实现多选效果的方法

使用v-model绑定数组

通过v-model绑定一个数组类型的变量,配合checkboxvalue属性实现多选。选中时值会自动添加到数组,取消选中时从数组移除。

vue实现多选效果

<template>
  <div>
    <label v-for="option in options" :key="option.value">
      <input 
        type="checkbox" 
        v-model="selectedItems" 
        :value="option.value"
      >
      {{ option.label }}
    </label>
  </div>
</template>

<script>
export default {
  data() {
    return {
      options: [
        { value: 'apple', label: 'Apple' },
        { value: 'banana', label: 'Banana' },
        { value: 'orange', label: 'Orange' }
      ],
      selectedItems: []
    }
  }
}
</script>

使用第三方组件库

Element UI或Ant Design Vue等库提供现成的多选组件,例如el-checkbox-group

vue实现多选效果

<template>
  <el-checkbox-group v-model="checkedList">
    <el-checkbox 
      v-for="item in options" 
      :key="item.value" 
      :label="item.value"
    >
      {{ item.label }}
    </el-checkbox>
  </el-checkbox-group>
</template>

自定义多选逻辑

通过事件手动管理选中状态,适合需要高度定制的场景:

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

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' }
      ],
      selectedIds: []
    }
  },
  methods: {
    toggleSelect(id) {
      const index = this.selectedIds.indexOf(id)
      index === -1 
        ? this.selectedIds.push(id) 
        : this.selectedIds.splice(index, 1)
    }
  }
}
</script>

表格多选

配合表格组件实现行选择功能,常用el-tableselection功能:

<el-table
  ref="multipleTable"
  :data="tableData"
  @selection-change="handleSelectionChange"
>
  <el-table-column type="selection" width="55"></el-table-column>
  <!-- 其他列 -->
</el-table>

<script>
export default {
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

注意事项

  • 对象类型作为value时需使用Vue.set确保响应式更新
  • 大量数据时考虑性能优化,如虚拟滚动
  • 移动端需注意触摸反馈和用户体验
  • 可结合computed属性实现全选/反选逻辑

标签: 多选效果
分享给朋友:

相关文章

vue实现对话框效果

vue实现对话框效果

使用 Vue 实现对话框效果 在 Vue 中实现对话框效果可以通过组件化方式完成,通常结合 v-if/v-show 控制显示隐藏,以及插槽(slot)实现内容自定义。 基础对话框组件实现 创建一个名…

vue实现效果

vue实现效果

Vue 实现常见效果的方法 数据绑定与响应式更新 Vue 的核心特性是数据绑定,通过 v-model 实现表单元素与数据的双向绑定。例如输入框与数据的实时同步: <input v-model=…

js实现图片滚动效果

js实现图片滚动效果

使用CSS动画实现图片滚动 通过CSS的@keyframes和animation属性实现无缝滚动效果。将图片容器设置为横向排列,通过动画平移位置。 <style> .scroll-c…

vue实现div多选

vue实现div多选

Vue 实现 Div 多选功能 基础实现思路 通过 Vue 的数据绑定和事件处理,可以轻松实现 div 的多选功能。核心是维护一个数组来存储选中的 div 的标识符,并通过 v-bind 和 v-on…

vue 实现列表多选

vue 实现列表多选

Vue 实现列表多选的方法 使用 v-model 绑定数组 通过 v-model 绑定一个数组,可以自动处理多选逻辑。适用于复选框(checkbox)场景。 <template> &…

vue实现旋转效果

vue实现旋转效果

使用CSS动画实现旋转 在Vue中可以通过CSS的@keyframes或transform属性实现旋转效果。在组件的<style>部分定义旋转动画: .rotate { animat…