当我更改一个变量的状态时,另一个变量会发生变化,而无需在 laravel 的 livewire 中调用它

When I change the state of a variable another one change without calling it in laravel's livewire

提问人:Emmanuel Sierra Morales 提问时间:11/17/2023 更新时间:11/17/2023 访问量:27

问:

我有这个问题:Imgr 视频问题

代码的逻辑是下一个(我使用的是livewire): 我有两个组件3.1.0

  • Table Component
  • Modal Component(附在Table Component)

表组件

// Blade
<div>
    // ...
    <button wire:click="openModal">Open Modal</button>
    
    @if($showModal)
        @livewire('modal-component')
    @endif
</div>

// Logic
public $showModal = false;
public function openModal(){ $this->showModal = true; }

#[On('close-modal')]
public function closeModal() {
    $this->showModal = false;
}

模态组件

// Logic
public $departmentValue, $departmentId, $departmentDropdown = false;

public function toogleDepartmentDropdown(){
    $this->departmentDropdown = !$this->departmentDropdown;
}

public function setDepartmentDropdown($id, $value){
    $this->departmentId = $id;
    $this->departmentValue = $value;
    $this->$departmentDropdown = false;
}

public function closeModal(){
    $this->dispatch('close-modal')
}
// Blade
<div>
    <button wire:click="closeModal">Icon Close Button</button>
    
    <button wire:click="toogleDepartmentDropdown">@if($departmentValue){{$departmentValue}}@else - @endif</button>
    @if($departmentDropdown)
        <div>
            @foreach(App\Models\Department::all() as $department)
                <button wire:click="setDepartmentDropdown('{{$department->id}}','{{$department->department_name}}')">{{$department->department_name}}</button>
            @endforeach
        </div>
    @endif
</div>

我不知道我是否必须使用,因为我已经用过它,但它不起作用,所以我不知道下一步要做什么。mount()

php laravel laravel-livewire

评论


答:

0赞 Pippo 11/17/2023 #1

您必须在@foreach中为每个<按钮>添加一个 wire:key

<button wire:click="setDepartmentDropdown('{{$department->id}}','{{$department->short_description}}')" wire:key="{{'dep-' . $department->id}}">

中也有一个错误

$this->$departmentDropdown = false;

那应该是

$this->departmentDropdown = false;

评论

0赞 Emmanuel Sierra Morales 11/17/2023
它不起作用,因为当我执行 的函数时,我再次单击以更改模态关闭状态,因为它更改了其他组件变量的值,因此它永久保持 on 的状态,而无需调用调用侦听器的函数toogleDepartmentDropdowndepartmentDropdownshowModaltruecloseModaldispatch('close-modal')
0赞 Pippo 11/17/2023
我用你的代码做了一个测试,它对我来说非常有效。也许与其他组件有一些相互作用?你能发布整体代码吗?