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

Livewire组件提交按钮触发Uncaught ReferenceError问题求助

问题排查与修复方案

你遇到的问题由多个错误叠加导致,以下是具体原因和修复步骤:

1. 控制台报错Uncaught ReferenceError: Dortmund is not defined的直接原因

Blade模板中表单提交的参数没有加引号:

<form wire:submit.prevent="getWeatherByCity({{$city}})">

这段代码渲染到前端后会变成getWeatherByCity(Dortmund),JS会把Dortmund识别为变量而非字符串,因此抛出未定义错误。

2. 提交后没有获取输入框新城市的原因

你没有将输入框和Livewire属性绑定,提交时传递的是页面渲染时的预设城市值,而非用户输入的新内容。

3. 前端无法调用getWeatherByCity方法的原因

组件类中getWeatherByCity是protected保护类型,只有public公开类型的方法才能被Livewire前端触发调用。

4. 方法内部逻辑错误

你定义的属性名为$currentWeatherRes、$forecastWeatherRes,但赋值时写成了$currentWeatherResp、$forecastWeatherResp,拼写不一致导致属性赋值失效;同时方法接收了$city参数,但调用接口时依然使用的是旧的$this->city属性,没有用到传入的新值。

修复后代码示例

1. Livewire Blade组件修改

仅需要修改表单部分即可:

<form wire:submit.prevent="getWeatherByCity">
    <input type="text" wire:model="city" name="city">
    <div>
        <x-form.button>Submit</x-form.button>
    </div>
</form>

去掉了错误的参数传递,给输入框加上wire:model绑定组件的$city属性,用户输入的内容会自动同步到后端组件。

2. Livewire组件类修改

class WeatherInfo extends Component 
{ 
    public $city; 
    // 修正属性拼写和赋值保持一致
    private $currentWeatherResp; 
    private $forecastWeatherResp;

    public function mount()
    {
        $this->city = auth()->user()->city ?? $this->city;
        $this->getWeatherByCity();
    }

    // 改为public公开方法,去掉不必要的传参(因为已经通过wire:model绑定了$city属性)
    public function getWeatherByCity()
    {
        $apiKey = config('services.openweather.key');
        // 直接用已经同步最新值的$this->city调用接口
        $this->currentWeatherResp = Http::get(
            "http://api.weatherapi.com/v1/current.json?&q={$this->city}&key={$apiKey}")->json();

        $this->forecastWeatherResp = Http::get(
            "http://api.weatherapi.com/v1/forecast.json?key={$apiKey}&q={$this->city}&days=7")->json();
    }

    public function render()
    {
        return view('livewire.weather-info', [
            'currentWeatherResp' => $this->currentWeatherResp,
            'forecastWeatherResp' => $this->forecastWeatherResp,
        ]);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:45:09