Livewire 表单内容消失

问题描述

我在包含表单的 livewire 视图中有此代码。这是一个简单的选择字段,您应该在其中从列表中选择文档类型。

<div>
    <label for="documenttype" class="form-label"><strong>Document type</strong></label>
    <select wire:model="documenttype_id" class="form-control" id="documenttype" aria-describedby="documenttypeHelp">
        <option selected>{{ __( 'Choose' ) }}</option>
        @foreach( $documenttypes as $documenttype )
            <option value="{{ $documenttype->id }}" @if( isset( $documenttype_id ) && ( $documenttype_id == $documenttype->id ) ) selected @endif>
                {{ $documenttype->name }}
            </option>
        @endforeach
    </select>
</div>

问题是我希望它在编辑客户端时预先选择了正确的值。但是出于某种原因,当我在选项循环中添加代码时:@if( isset( $documenttype_id ) && ( $documenttype_id == $documenttype->id ) ) selected @endif,表单开始出现奇怪的行为。 每次填写表单的人选择一个选项时,内容都会变为空白。

这是情况 1(在选择选项之前):

enter image description here

这是情况2(选择选项后):

enter image description here

我不知道为什么会发生这种情况,有人可以指导我如何解决这个问题吗?

解决方法

解决此问题的快速方法是从您的组件 mount 方法中分配选定的值。

public function mount() {

    $this->documenttype_id = $client->documenttype_id
    //$client->documenttype_id being the previously selected value from your db
}

这将自动选择您的选项,您不需要选项标签上的 if 语句。