Laravel Nova Value Metric:如何将数值下降设为良性变化
实现Laravel Nova Value Metric负面上升箭头变红
可以实现,有两种常用方案:
方案一:在Metric类中手动控制趋势颜色
放弃Nova自动的趋势计算逻辑,手动计算当前值与历史值的变化,根据需求(数值上升为负面)指定箭头颜色:
<?php namespace App\Nova\Metrics; use Illuminate\Http\Request; use Laravel\Nova\Metrics\Value; class NegativeTrendValue extends Value { public function calculate(Request $request) { // 替换为你的实际数值计算逻辑 $currentCount = \App\Models\YourModel::where('status', 'pending')->count(); $lastMonthCount = \App\Models\YourModel::where('status', 'pending') ->whereMonth('created_at', now()->subMonth()->month) ->count(); $change = $currentCount - $lastMonthCount; $changePercent = $lastMonthCount > 0 ? round(($change / $lastMonthCount) * 100, 2) : 0; // 数值上升(change为正)时用红色,下降用绿色 $trendColor = $change > 0 ? 'red' : 'green'; return $this->result($currentCount) ->trend($change, $changePercent) ->color($trendColor); } public function name() { return '待处理任务数'; } }
这种方法的优势是可以针对单个Metric单独配置,不会影响其他Metric的样式。
方案二:全局CSS覆盖默认样式
如果需要所有符合“上升为负面”规则的Value Metric都生效,可以通过自定义CSS覆盖Nova的默认样式:
- 在项目根目录的
resources/css下创建nova.css文件,添加以下样式:
/* 将上升趋势的箭头/数值改为红色 */ .metric-value .trend.up { color: #ef4444 !important; } .dark .metric-value .trend.up { color: #f87171 !important; } /* 可选:将下降趋势的箭头/数值改为绿色(保持默认也可以) */ .metric-value .trend.down { color: #10b981 !important; } .dark .metric-value .trend.down { color: #34d399 !important; }
- 修改
nova.mix.js文件,引入这个CSS:
mix.js('resources/js/nova.js', 'public/js') .postCss('resources/css/nova.css', 'public/css', [ require('tailwindcss'), ]);
- 运行
npm run dev编译资源,Nova就会加载自定义样式。
这种方法适合全局统一修改趋势颜色的场景,但要注意会影响所有Value Metric的上升趋势样式。
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

