You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Livewire编辑页Select2多选组件已选值未在输入框显示问题

问题原因

你用wire:ignore包裹了Select2的容器,Livewire不会主动更新该区域的DOM渲染,Select2初始化时没有同步后端返回的初始选中值到展示层,仅原生option的选中属性被正确设置,所以出现下拉可看到高亮、但输入框无选中标签的现象。另外若后端返回的选中ID是字符串格式,和option的数字ID类型不匹配也会触发该问题。

修复方案

1. 修改Livewire组件mount方法

将选中的ID统一转为数字类型,和option的value类型保持匹配:

public $home_categories = [];
public $no_of_products;

public function mount()
{
    $category = HomeCategory::all()->first();
    // 把拆分后的字符串ID转为数字
    $this->home_categories = array_map('intval', explode(',', $category->home_categories));
    $this->no_of_products = $category->no_of_products;
}

2. 修改Select2初始化脚本

初始化时主动同步Livewire的初始选中值到Select2组件:

@push('scripts')
<script>
    $(document).ready(function() {
        const $select2 = $('.select2');
        $select2.select2();
        
        // 同步初始选中值
        $select2.val(@js($home_categories)).trigger('change');

        // 选中值变更同步到Livewire
        $select2.on('change', function (e) {
            @this.set('home_categories', $(this).select2("val"));
        });
    });
</script>
@endpush

内容的提问来源于stack exchange,提问作者Bharath-CODER

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 20:15:03