You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel 5.5 + Vue.js + Axios中用复选框批量删除多行数据

实现Laravel 5.5 + Vue.js + Buefy 复选框批量删除条目功能

结合你给出的技术栈和部分代码,我帮你完善整套批量删除的实现方案,从前端Vue组件到后端Laravel接口都梳理清楚:


一、完整Vue组件实现

1. 模板部分(补全并优化)

我用Buefy的b-table组件来实现带复选框的列表,它原生支持选中行同步,非常方便:

<template>
  <section class="container mt-5">
    <!-- 操作按钮组 -->
    <div class="mb-4">
      <button 
        class="button is-small is-danger mr-2" 
        @click="checkedRows = []" 
        :disabled="!checkedRows.length"
      >
        <b-icon icon="close"></b-icon>
        <span>Clear checked</span>
      </button>
      <button 
        class="button is-small is-danger" 
        @click.prevent="onDelete" 
        title="Delete checked" 
        :disabled="!checkedRows.length"
      >
        <b-icon icon="trash"></b-icon>
        <span>Delete Selected</span>
      </button>
    </div>

    <!-- 带复选框的数据列表 -->
    <b-table
      :data="items"
      :checked-rows.sync="checkedRows"
      checkbox-column
      hoverable
    >
      <!-- 自定义列示例,你可以根据自己的需求修改 -->
      <b-table-column field="name" label="Item Name" sortable></b-table-column>
      <b-table-column field="description" label="Item Description"></b-table-column>
      <b-table-column field="created_at" label="Created At" format="date"></b-table-column>
    </b-table>
  </section>
</template>

2. 脚本逻辑部分

这里包含数据加载、批量删除的核心逻辑,用Axios和Buefy的通知/弹窗组件提升用户体验:

<script>
import axios from 'axios'

export default {
  name: 'ItemList',
  data() {
    return {
      items: [], // 存储列表数据
      checkedRows: [] // 存储选中的行数据,和b-table的checked-rows.sync绑定
    }
  },
  mounted() {
    // 页面加载时获取数据
    this.loadItems()
  },
  methods: {
    // 从后端获取列表数据
    async loadItems() {
      try {
        const response = await axios.get('/api/items')
        this.items = response.data
      } catch (err) {
        console.error('加载数据失败:', err)
        this.$buefy.notification.open({
          message: 'Failed to load items',
          type: 'is-danger',
          duration: 5000
        })
      }
    },
    // 批量删除操作
    async onDelete() {
      // 先弹出确认框,防止误删
      const isConfirmed = await this.$buefy.dialog.confirm({
        title: 'Confirm Bulk Delete',
        message: `Are you sure you want to delete ${this.checkedRows.length} selected item(s)?`,
        confirmText: 'Delete',
        cancelText: 'Cancel',
        type: 'is-danger'
      })

      if (!isConfirmed) return

      try {
        // 提取选中条目的ID数组
        const itemIds = this.checkedRows.map(row => row.id)
        // 调用后端批量删除接口
        await axios.post('/api/items/batch-delete', { ids: itemIds })

        // 更新前端列表,移除已删除的条目
        this.items = this.items.filter(item => !itemIds.includes(item.id))
        // 清空选中状态
        this.checkedRows = []

        // 显示成功通知
        this.$buefy.notification.open({
          message: 'Selected items deleted successfully!',
          type: 'is-success',
          duration: 4000
        })
      } catch (err) {
        console.error('批量删除失败:', err)
        this.$buefy.notification.open({
          message: 'Failed to delete items',
          type: 'is-danger',
          duration: 5000
        })
      }
    }
  }
}
</script>

二、Laravel后端实现

1. 定义API路由(routes/api.php)

添加获取列表和批量删除的路由:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/items', 'ItemController@index');
Route::post('/items/batch-delete', 'ItemController@batchDelete');

2. 控制器逻辑(app/Http/Controllers/ItemController.php)

实现数据获取和批量删除的方法,同时做参数验证:

<?php

namespace App\Http\Controllers;

use App\Item;
use Illuminate\Http\Request;

class ItemController extends Controller
{
    // 获取所有条目数据
    public function index()
    {
        return Item::all();
    }

    // 批量删除条目
    public function batchDelete(Request $request)
    {
        // 验证传入的ID数组
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:items,id' // 确保每个ID都存在于items表中
        ]);

        // 执行批量删除
        Item::whereIn('id', $request->ids)->delete();

        return response()->json([
            'message' => 'Items deleted successfully'
        ], 200);
    }
}

三、关键注意事项

  • Buefy表格配置:确保b-table的checkbox-column属性开启,checked-rows.sync绑定到你的数据变量,这样才能自动同步选中的行。
  • 用户体验优化:添加删除确认弹窗和操作通知,让用户清楚知道操作结果。
  • 后端验证:一定要对传入的ids数组做验证,防止无效ID或者恶意请求。
  • 状态同步:删除成功后要更新前端列表并清空选中状态,保证界面和数据一致。
  • 错误处理:对异步请求添加错误捕获,避免页面崩溃,同时给用户友好的错误提示。

内容的提问来源于stack exchange,提问作者Anton Sirik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:26:46