Laravel / Livewire - Modal删除第一行

fnatzsnv  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(94)

基本上我正在从数据库中获取一些数据,我有一个删除按钮,弹出一个确认模式。
我点击删除后,它删除了错误的id,不管我想删除它总是先删除行。
这是我的循环:

@forelse ($allTypes as $type)
    <tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
        <th scope="row" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
            {{ $type->id }}
        </th>

      //other <th> tags
    </tr>

<td class="py-4 w-1/4">
    <button data-modal-target="popup-modal" data-modal-toggle="popup-modal" type="button">
          Delete
    </button>
</td>

正如你所看到的,我在按钮中使用了data-modal-target="popup-modal" data-modal-toggle="popup-modal"
我猜问题来自data-modal-target="popup-modal",但我不确定在那里添加什么。
以及modal:

<div id="popup-modal" tabindex="-1" class="fixed top-0 left-0 right-0 z-50 hidden p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full flex justify-center items-center">
    <button wire:click = "deleteType({{ $type->id }}) data-modal-hide="popup-modal" type="button" class="text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2">
           Yes, delete!
     </button>
</div>

现在我删除了所有不必要的设计类,所以我不想让你感到困惑。
这是我的删除方法:

public function deleteType($typeID)
{
    $types = Types::findOrFail($typeID);
    $types->delete();
    $this->allTypes = $this->fetchTypes();
}

在我点击Yes, delete!后,第一行被删除,而不是选中的一行,我该如何克服这个问题?

brjng4g3

brjng4g31#

你错过了一些东西,我没有看到任何地方selectedId删除.假设你只有一个模态(你应该)所以wire:click = "deleteType({{ $type->id }})"总是相同的(或第一行或最后一行).
我的方法应该是声明一个变量,当你点击删除按钮时它会改变:
在Livewire类中:

...
    public $selectForDeleteingType = 0;
    ...
    public function changeDelete($type){
        $this->selectedForDeletingType = $type;
    }
    public function deleteType()
    {
        if($this->selectedForDeletingType == 0){
              return;
        }
        $types = Types::findOrFail($this->selectForDeletingType);
        $types->delete();
        $this->allTypes = $this->fetchTypes();
        $this->selectForDeletingType = 0;
    }
    ...

表中的按钮:

<button wire:click="changeDelete({{$type->id}})" data-modal-target="popup-modal" data-modal-toggle="popup-modal" type="button">
          Delete
</button>

然后在模态中的按钮:

<div id="popup-modal" tabindex="-1" class="fixed top-0 left-0 right-0 z-50 hidden p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full flex justify-center items-center">
    <button wire:click="deleteType()" data-modal-hide="popup-modal" type="button" class="text-white bg-red-600 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 dark:focus:ring-red-800 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center mr-2">
           Yes, delete!
     </button>
</div>

如果没有,它应该100%工作,也许使用一些关键索引和一些alpinejs应该可以完成这项工作。

相关问题