Livewire Select2 Dynamic 未更新公共视图
我正在使用带有
wire:ignore
的 select2 组件,我想在单击按钮后动态更新 select2 值。我使用事件设置了此功能,事件运行正常,变量也初始化正常。我无法更新此 select2 的公共视图。
我的 blade
<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
到目前为止,我也尝试过使用浏览器调度事件。没有任何效果。有什么解决方法吗?非常感谢任何帮助。
在 blade 中
<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');
}
注意:如果某些人在实施上述解决方案时遇到实时验证的问题,正如我在上面接受的答案中所评论的那样。
我的评论:
hey, I have implemented your solution its working great but there is one problem, here is the scenario, I submit empty form and all the validations gets triggered, when i start filling the form the error starts to disappear but as soon as i change the select2 the validation part $this-update($key, $value) function does not work. Can you please tell me why real time validation is not working ? and how to fix it please. thankyou – Wcan
解决方案:
使用 syncInput() 函数,而不是将值分配给 country 属性。更新的生命周期钩子将自动触发。
public function setCountry($countryValue)
{
// $this->country = $countryValue;
$this->syncInput('country', $countryValue);
}