【问题标题】:How to get data only if the data is not filled in front-end using livewire and alpinejs?前端没有使用livewire和alpinejs填充数据,如何获取数据?
【发布时间】: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-&gt;states[$country] 已经具有值并且可以使用 alpinejs 访问时,如何防止它多次请求?

例如,我在&lt;select&gt; 中选择美国。它第一次需要获取作为其状态的数据。我把它改成加拿大。这次它需要获取它的状态数据。但是如果我再次选择美国,它不应该请求,因为它已经获取并且在 alpinejs 中可用。我怎样才能实现它?

【问题讨论】:

    标签: javascript php optimization laravel-livewire alpine.js


    【解决方案1】:

    我认为您必须使用 alpinejs 手动验证。

    <div x-data="{
        selectedCountry: null,
        countries: {},
    }"
    x-init="$watch('selectedCountry', () => {
        if(! (selectedCountry in countries)) {
            @this.call('fillStates');
            countries[selectedCountry] = @this.get('states');
        }
    })"
    >
    <select x-model="selectedCountry" name="selectedCountry" id="selectedCountry" >
        <option value="">Select Country</option>
        @foreach($this->countries as $country)
            <option value="{{ $country->id }}">{{ $country->name }}</option>
        @endforeach
    </select>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 2021-12-23
      • 1970-01-01
      • 2020-04-06
      • 2017-03-19
      • 2020-01-07
      • 2017-08-01
      • 2021-04-30
      • 2021-08-28
      相关资源
      最近更新 更多