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

如何在victorybiz/laravel-tel-input的Livewire组件中填充数据

解决Laravel Tel Input在Livewire中填充初始数据的问题

步骤1:调整Livewire组件的属性定义

把原来存在$data数组中的字段改成public属性,才能和wire:model正确绑定:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class YourComponent extends Component
{
    // 定义与视图绑定的public属性
    public $phone;
    public $phone_country;

    public function mount()
    {
        $user = optional(auth()->user());
        
        // 拆分区号和手机号
        $this->phone_country = str_replace("+", "", $user->country_code);
        $this->phone = str_replace($this->phone_country, '', $user->phone_no);
    }

    public function render()
    {
        return view('livewire.your-component-view');
    }
}

步骤2:给Tel Input组件传递初始值

直接在Blade视图的x-tel-input组件上添加value和country-code属性,利用Livewire的属性值填充初始数据:

<x-tel-input
    wire:model="phone"
    id="phone"
    name="phone"
    class="form-input"
    value="{{ $phone }}"
    country-code="{{ $phone_country }}"
/>
<input wire:model="phone_country" type="hidden" id="phone_country" name="phone_country">

备选方案:用JS API初始化(适配组件底层的intl-tel-input)

如果上述方法不生效,可利用组件基于intl-tel-input的特性,通过JS直接设置完整号码,组件会自动拆分区号和手机号:

<x-tel-input
    wire:model="phone"
    id="phone"
    name="phone"
    class="form-input"
/>
<input wire:model="phone_country" type="hidden" id="phone_country" name="phone_country">

@push('scripts')
<script>
// 监听Livewire初始化完成事件
document.addEventListener('livewire:initialized', function() {
    const telInput = document.getElementById('phone');
    // 获取tel-input实例
    const iti = window.intlTelInputGlobals.getInstance(telInput);
    
    // 设置用户的完整手机号,组件会自动解析区号和号码部分
    iti.setNumber('{{ optional(auth()->user())->phone_no }}');

    // 同步区号到hidden字段(如果组件没有自动同步)
    telInput.addEventListener('countrychange', function() {
        document.getElementById('phone_country').value = iti.getSelectedCountryData().dialCode;
    });
});
</script>
@endpush

注意事项

  • 确保auth()->user()能正确获取当前用户,且用户模型包含country_code和phone_no字段
  • 如果使用JS方案,需确保页面已正确加载intl-tel-input的依赖资源(组件包通常会自动引入)

内容的提问来源于stack exchange,提问作者Noman Zahid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 07:00:14