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

动态调整Bootstrap进度条类:按宽度切换警告/成功样式

解决动态切换Bootstrap进度条类的问题

嘿,这问题我之前也碰到过,其实用Vue的动态类绑定就能轻松搞定!你现在的进度条类是固定写死的,我们只需要根据customerLoan.progress的值来动态切换对应的Bootstrap类就行。

核心修改思路

用Vue的:class(v-bind:class的简写)语法,结合三元表达式判断进度值:

  • 当progress ≤ 50时,添加progress-bar-warning类
  • 当progress > 50时,添加progress-bar-success类

同时要处理progress为空/未定义的情况(你代码里用了|| "0"),所以判断时要加上兜底,避免报错。

修改后的完整HTML代码

<td>
  <span class="header-text">
    <div 
      :class="[
        'progress-bar progress-bar-striped active progressbartextcolor',
        (customerLoan.progress || 0) <= 50 ? 'progress-bar-warning' : 'progress-bar-success'
      ]"
      id="progressbarcolorchange" 
      role="progressbar" 
      aria-valuenow="25" 
      aria-valuemin="0" 
      v-bind:style="{width: `${customerLoan.progress || 0}%`}" 
      aria-valuemax="100"
    >{{customerLoan.progress || "0"}}%</div>
  </span>
</td>

关键修改点说明

  1. 动态类绑定:把原来固定的class换成:class,用数组形式同时保留基础样式类和动态切换的类
  2. 兜底判断:用(customerLoan.progress || 0)确保即使progress为空,也会用0来判断,避免出现undefined <=50的报错
  3. 宽度绑定优化:把width: customerLoan.progress + '%'改成模板字符串${customerLoan.progress || 0}%,同样处理空值情况

Vue代码无需修改

你的Vue实例部分已经正确加载了customerLoans数据,只要确保progress字段是数字类型(如果是字符串的话,比如从接口返回的是字符串,就改成parseInt(customerLoan.progress) || 0),就能正常工作啦!

测试一下:当进度是25%时,进度条会是警告色;当进度超过50%(比如60%),就会自动变成成功色,完美符合你的需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:28:36