【发布时间】:2021-12-22 18:59:03
【问题描述】:
为了使用更少的资源,我只想第一次从服务器(使用 livewire)获取数据,其他时间使用 alpinejs 中已经获取的数据。
所以如果我的<select>有变化,fillStates就会被触发:
<select wire:model="selectedCountry" name="selectedCountry" id="selectedCountry" wire:change="fillStates">
<option value="">Select Country</option>
@foreach($this->countries as $country)
<option value="{{ $country->id }}">{{ $country->name }}</option>
@endforeach
</select>
fillStates 方法将返回数据:
public function fillStates()
{
$states = State::where('country_id', $this->selectedCountry)->get();
if(count($states)) {
$this->states[$this->selectedCountry] = $states;
return $this->states[$this->selectedCountry];
}
return [];
}
我的问题就在这里。当$this->states[$country] 已经具有值并且可以使用 alpinejs 访问时,如何防止它多次请求?
例如,我在<select> 中选择美国。它第一次需要获取作为其状态的数据。我把它改成加拿大。这次它需要获取它的状态数据。但是如果我再次选择美国,它不应该请求,因为它已经获取并且在 alpinejs 中可用。我怎样才能实现它?
【问题讨论】:
标签: javascript php optimization laravel-livewire alpine.js