首页 > 解决方案 > Livewire Select2 Dynamic 不更新公共视图

问题描述

我正在使用 select2 组件,wire:ignore并且我想在单击按钮后动态更新 select2 值。我使用事件设置了这个功能,并且事件工作正常,变量也被初始化。我未能更新此 select2 的公开视图。

我的刀片

<select class="select2-example form-control" id="subjects" wire:model.lazy="subjects"  name="subjects"> 
 </select> 

@push('scripts')
<script>
$('#subjects').select2({
        maximumSelectionLength: 1,
        minimumInputLength:2,        
        tags: false,
        placeholder: 'Enter Subject(s)',
       .... // this all works great
});   

$('#subjects').on('change', function (e) {
        let data = $(this).val();
        @this.set('subjects', data);
});

// my event listener and it is working as well
Livewire.on('editSubject', subject => {
         console.log(subject);

         @this.set('subjects', subject);
         $('#subjects').val(subject);
         $('#subjects').trigger('change');   //the public view doesn't get updated
}) 
</script>
@endpush

到目前为止,我也尝试过浏览器调度事件。没有任何效果。解决方法是什么?任何帮助是极大的赞赏。

标签: laravellaravel-livewire

解决方案


在刀片

<div class="col d-flex display-inline-block">
  <label for="contact_devices">{{ __('Select Device') }}</label>
  <select id="contact_devices" wire:model="selectedDevice" class="form-control contact_devices_multiple" multiple="multiple" data-placeholder="{{ __('Select') }}">
    @foreach($devices as $device)
      <option value="{{ $device->id }}">{{ $device->alias }}</option>
    @endforeach
  </select>
</div>

<script>
  window.loadContactDeviceSelect2 = () => {
    $('.contact_devices_multiple').select2({
      // any other option
    }).on('change',function () {
      livewire.emitTo('tenant.contact-component','devicesSelect',$(this).val());
    });
  }
  loadContactDeviceSelect2();
  window.livewire.on('loadContactDeviceSelect2',()=>{
    loadContactDeviceSelect2();
  });

</script>

在组件中

public $selectedDevice;

protected $listeners = [
  'devicesSelect'
];

public function devicesSelect($data)
{
   dd($data);
   $this->selectedDevice = $data;
}

public function hydrate()
{
  $this->emit('loadContactDeviceSelect2');
}

推荐阅读