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

Livewire 3中style属性width值无法随变量动态更新求助

Livewire 3进度条style宽度不更新问题的原因及解决方法

原因

问题核心在于Livewire的DOM更新机制:直接用Blade插值{{ $campaign->progress }}绑定到内联style属性时,Livewire的DOM diff算法无法精准识别这个样式值的变化,导致仅文本内容能正常更新,而style中的宽度值停留在初始渲染状态,无法随变量动态刷新。

解决方法

以下是几种可靠的修复方案,按推荐优先级排序:

1. 使用Livewire专属的wire:style指令(推荐)

Livewire 3提供了wire:style指令,专门用于动态绑定样式属性,能完美追踪变量变化并同步更新DOM:

<div wire:poll class="relative h-5 w-full rounded-full bg-stroke dark:bg-strokedark">
    <div class="absolute left-0 h-full rounded-full bg-primary" wire:style="width: {{ $campaign->progress }}%">
        <span class="absolute -right-4 bottom-full z-1 mb-2 inline-block rounded-sm bg-primary px-2 py-1 text-xs font-bold text-white">
            <span class="absolute -bottom-1 left-1/2 -z-1 h-2 w-2 -translate-x-1/2 rotate-45 bg-primary"></span>
            {{ $campaign->progress }}%
        </span>
    </div>
</div>

2. 将进度值提取为组件公共属性

若$campaign是Eloquent模型,可在组件类中定义公共属性存储进度值,确保Livewire能直接追踪其变化:

// 组件类代码
public $progress;
public $campaign;

public function mount($campaign)
{
    $this->campaign = $campaign;
    $this->progress = $campaign->progress;
}

// 配合poll主动刷新进度
public function refreshProgress()
{
    $this->campaign->refresh(); // 刷新模型数据
    $this->progress = $this->campaign->progress;
}

视图中对应修改:

<div wire:poll="refreshProgress" class="relative h-5 w-full rounded-full bg-stroke dark:bg-strokedark">
    <div class="absolute left-0 h-full rounded-full bg-primary" style="width: {{ $this->progress }}%">
        <!-- 其余内容保持不变 -->
    </div>
</div>

3. 添加wire:key强制识别DOM元素

给进度条内层div添加唯一wire:key,帮助Livewire准确识别该元素,避免diff过程中忽略样式更新:

<div wire:poll class="relative h-5 w-full rounded-full bg-stroke dark:bg-strokedark">
    <div wire:key="campaign-progress-{{ $campaign->id }}" class="absolute left-0 h-full rounded-full bg-primary" style="width: {{ $campaign->progress }}%">
        <!-- 其余内容保持不变 -->
    </div>
</div>

内容的提问来源于stack exchange,提问作者Jean François Manatane

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:07:22