Laravel Livewire切换每页条数后,如何清除视图多余数据?
问题描述
我有一个Laravel Livewire组件,数据来自json.gz而非Laravel模型,需实现自定义分页等功能。组件中有下拉选择框,可切换每页显示10/50/100条数据,默认值为10。
问题:从10条切换到50条时正常,但从50条切换回10条时,数据视图仍显示50条(前10条已更新,但11-50条残留)。尝试过用$refresh刷新组件视图,但未解决问题。
相关代码
视图选择框代码
<div> <select wire:change="changeCountRows($event.target.value)" class="form-select form-select-sm form-select-solid w-100px"> <option value="10">10</option> <option value="50">50</option> <option value="100">100</option> </select> </div>
组件核心代码
render()方法
public function render() { if($this->items_json == null || $this->prev_search !== $this->search) { $this->getDatasJson(); $this->prev_search = $this->search; } $this->arrayChunkJson($this->items_json, $this->filterEntries); if($this->page_custom >= $this->end_page){ $this->end_page = $this->page_custom+1; $this->start_page = $this->page_custom - 4; }elseif ($this->page_custom < $this->start_page) { $this->start_page = $this->page_custom; $this->end_page = $this->page_custom + 5; } $datas = $this->single_cat[$this->page_custom]; $this->last_total_cat = array_keys($datas)[0] + 1; $this->total_cat_show = $this->last_total_cat + ($this->filterEntries - 1); // dd($this->single_cat); return view('livewire.kategori.single-kategori-mobile', [ 'single_cats' => $this->single_cat[$this->page_custom], 'page' => $this->page_custom, 'total_page' => $this->total_page, 'start_page' => $this->start_page, 'end_page' => $this->end_page, 'total_cat' => $this->total_cat, 'last_total_cat' => $this->last_total_cat, 'total_cat_show' => $this->total_cat_show ]); }
changeCountRows()方法
public function changeCountRows($filterEntries){ $this->filterEntries = $filterEntries; $this->emit('refresh_me'); }
监听器
protected $listeners = ['refresh_me' => '$refresh'];
视图渲染数据代码
<div class="flex flex-col" wire:loading.class="loading"> {{-- @dd(count($single_cats)); --}} @foreach($single_cats as $val) my data @endforeach </div>
解决方案
1. 切换每页条数时重置当前页码
当从50条切回10条时,若当前页码大于新的总页数,会读取到旧的分块数据;即使页码正常,重置到第一页也能避免DOM对比异常。修改changeCountRows方法:
public function changeCountRows($filterEntries){ $this->filterEntries = $filterEntries; $this->page_custom = 1; // 重置到第一页 // 移除emit操作,修改组件属性后Livewire会自动触发render刷新 }
2. 确保分块数据完全重置
检查arrayChunkJson方法,确保每次分块前清空旧的single_cat数组,避免残留旧分页数据:
private function arrayChunkJson($items, $perPage) { $this->single_cat = []; // 先清空旧数据 $chunks = array_chunk($items, $perPage); foreach ($chunks as $index => $chunk) { $this->single_cat[$index + 1] = $chunk; // 页码从1开始 } $this->total_page = count($this->single_cat); }
3. 给循环元素添加唯一wire:key
Livewire依赖wire:key识别DOM元素,没有key的话,数组长度减小时旧DOM元素无法被正确移除。修改视图循环代码:
<div class="flex flex-col" wire:loading.class="loading"> @foreach($single_cats as $key => $val) <div wire:key="category-item-{{ $key }}"> my data </div> @endforeach </div>
内容的提问来源于stack exchange,提问作者Fajar Alam
相关产品推荐
相关产品推荐

