首页 > 解决方案 > 无法使用带有 livewire 的关联键从数组中删除输入字段

问题描述

我有一个不容易解释的活线问题,但我会尽力而为。基本上,我正在使用来自序列化记录的键值对数组做一个动态表单。用户应该能够添加和删除新字段。问题在于 remove 方法,因为它似乎不接受密钥作为参数。我有什么办法可以处理这个?这是 livewire 组件:

class SetPositions extends Component
{
    protected $listeners = ['updatePositions' => 'render'];
    public $positions = [];
    public $key;
    public $value;
    public function mount(){
        $this->positions = Settings::where('name', '=', 'PEOPLE_POSITIONS')->pluck('value')->first();
    }

    public function addPosition() {
        $this->positions[$this->key] = $this->value;
        $this->emit('updatePositions');
    }

    public function removePosition($param){
        dd($param);
    }

    
    <form method="post" wire:submit.prevent="update">
            @csrf
            @method('PUT')
            @foreach($this->positions as $key => $value)
            <div x-data="{ block: false}" class="sm:grid sm:grid-cols-3 sm:gap-4 sm:items-start sm:border-t sm:border-gray-200 sm:pt-5">
                <div x-show="!block" class="block text-sm font-medium text-gray-700 sm:mt-px sm:pt-2">
                    <!--<input :disabled="!block" value="" type="text" class="block w-full max-w-lg border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm">-->
                    <label for="test" class="block w-full max-w-lg border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm">
                        {{$key}}
                    </label>
                </div>
                <div x-show="!block" class="mt-1 sm:mt-0 sm:col-span-1">
                    <input wire:model="positions.{{$key}}" type="text" class="block w-full max-w-lg border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm">
                </div>
                <button wire:click="removePosition({{$positions[$key]}})" @click="block = !block" type="button">
                    <svg class="w-6 h-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
            </div> 
            @endforeach

标签: laravellaravel-livewire

解决方案


查看 Laravel 文档中的 pluck 方法。现在您可以将位置属性作为具有键值对的数组处理 https://laravel.com/docs/8.x/collections#method-pluck


推荐阅读