当前位置:首页 > VUE

vue 实现多选全选

2026-02-20 14:22:56VUE

Vue 实现多选全选功能

多选全选功能在表格或列表中很常见,以下是实现方法:

基础实现

  1. 定义数据模型

    data() {
    return {
     items: [
       { id: 1, name: 'Item 1', selected: false },
       { id: 2, name: 'Item 2', selected: false },
       { id: 3, name: 'Item 3', selected: false }
     ],
     selectAll: false
    }
    }
  2. 全选逻辑

    vue 实现多选全选

    methods: {
    toggleSelectAll() {
     this.items.forEach(item => {
       item.selected = this.selectAll
     })
    }
    }
  3. 模板部分

    <template>
    <div>
     <label>
       <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
       全选
     </label>
    
     <div v-for="item in items" :key="item.id">
       <label>
         <input type="checkbox" v-model="item.selected">
         {{ item.name }}
       </label>
     </div>
    </div>
    </template>

高级实现(带反向检查)

  1. 计算属性检查全选状态

    vue 实现多选全选

    computed: {
    selectAll: {
     get() {
       return this.items.length > 0 && this.items.every(item => item.selected)
     },
     set(value) {
       this.items.forEach(item => {
         item.selected = value
       })
     }
    }
    }
  2. 简化模板

    <template>
    <div>
     <label>
       <input type="checkbox" v-model="selectAll">
       全选
     </label>
    
     <div v-for="item in items" :key="item.id">
       <label>
         <input type="checkbox" v-model="item.selected">
         {{ item.name }}
       </label>
     </div>
    </div>
    </template>

表格场景实现

  1. 表格结构实现

    <template>
    <table>
     <thead>
       <tr>
         <th>
           <input type="checkbox" v-model="selectAll">
         </th>
         <th>名称</th>
         <th>价格</th>
       </tr>
     </thead>
     <tbody>
       <tr v-for="item in items" :key="item.id">
         <td><input type="checkbox" v-model="item.selected"></td>
         <td>{{ item.name }}</td>
         <td>{{ item.price }}</td>
       </tr>
     </tbody>
    </table>
    </template>
  2. 获取选中项方法

    methods: {
    getSelectedItems() {
     return this.items.filter(item => item.selected)
    }
    }

注意事项

  • 当使用v-for渲染列表时,确保为每个元素设置唯一的key属性
  • 大型数据集考虑性能优化,可能需要使用虚拟滚动
  • 选中状态变化可以触发watch监听器执行后续操作

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

相关文章

jquery 多选

jquery 多选

jQuery 多选实现方法 使用 prop() 方法实现多选 通过 prop() 方法可以批量设置多个复选框的选中状态。以下是一个示例代码: $('input[type="checkbox"]').…

vue实现循环多选

vue实现循环多选

实现循环多选的方法 使用v-for渲染选项 通过v-for循环渲染复选框或列表项,绑定v-model到数组实现多选。例如: <template> <div v-for="ite…

js 多选 实现

js 多选 实现

实现多选的 JavaScript 方法 使用复选框(Checkbox)实现多选 通过 HTML 的 checkbox 元素配合 JavaScript 实现多选功能。用户可以选择多个选项,提交时获取所有…

vue实现多选效果

vue实现多选效果

Vue 实现多选效果的方法 使用 v-model 绑定数组 在 Vue 中,可以通过 v-model 绑定一个数组来实现多选效果。适用于复选框组(checkbox)或下拉多选(select multi…

vue实现点击多选

vue实现点击多选

实现点击多选的基本逻辑 在Vue中实现点击多选功能,通常需要维护一个数组来存储已选中的项,并通过点击事件动态更新该数组。核心逻辑包括数据绑定、事件处理和状态更新。 <template>…

vue实现按钮多选

vue实现按钮多选

实现按钮多选功能 在Vue中实现按钮多选功能,可以通过以下方法完成。这里提供两种常见的实现方式:基于数组管理和使用v-model绑定。 基于数组管理选中状态 定义一个数组来存储选中的按钮值,…