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

Vue.js根据三个条件实现文本颜色动态切换问题求助

问题描述

我有一个包含Firenze、Roma、Milano三种取值的表格,需要为每个值关联不同颜色,页面加载时就要渲染对应颜色。由于内联条件渲染仅支持两个值,我尝试使用以下函数实现($missing_item是来自外部数组prop $missing_items的v-for单个项):

function getColour($missing_item){
    switch($missing_item.Deposito){
        case $missing_item.Deposito == 'Firenze':
            return 'text-violet-400';
        case $missing_item.Deposito == 'Roma':
            return 'text-orange-400';
        case $missing_item.Deposito == 'Milano':
            return 'text-green-400';
    }
}

调用方式为:class="changeColour()",但始终报错:

"Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'Deposito')"

核心问题:如何在函数中访问v-for渲染的$missing_item.Deposito属性。

解决方法
  • 修正函数调用传参
    你调用函数时没传递$missing_item参数,导致函数内部的$missing_item是undefined,自然无法读取Deposito属性。同时你调用的函数名changeColour和定义的getColour不匹配,把调用改成:
:class="getColour($missing_item)"
  • 修正switch语句语法
    你的switch写法错误,case后面应该直接写匹配的具体值,不需要再加判断表达式:
function getColour($missing_item){
    switch($missing_item.Deposito){
        case 'Firenze':
            return 'text-violet-400';
        case 'Roma':
            return 'text-orange-400';
        case 'Milano':
            return 'text-green-400';
        default: // 建议添加默认值,避免出现未匹配项时的异常
            return '';
    }
}
  • 添加安全校验(可选)
    如果$missing_item可能为undefined或null,可以在函数开头加一层判断,提前规避报错:
function getColour($missing_item){
    if(!$missing_item?.Deposito) return '';
    switch($missing_item.Deposito){
        case 'Firenze':
            return 'text-violet-400';
        case 'Roma':
            return 'text-orange-400';
        case 'Milano':
            return 'text-green-400';
        default:
            return '';
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:35:33