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

如何使用Vue组合式API的计算属性根据文本切换胶囊样式颜色?

Vue组合式API实现状态胶囊背景色切换

问题

我有一个胶囊形状的文本块,显示内容为Production或Development,希望根据显示内容切换背景颜色。之前用选项式API实现过,但组合式API里遇到了问题。

原代码中的核心错误

  1. 脚本里的dashboard是数组,但计算属性直接访问dashboard.status——数组本身没有该属性,需访问数组内的具体对象(如dashboard[0].status)
  2. 模板中拼写错误:{{ dashboards.status }}多了s,应为dashboard[0].status
  3. 原计算属性未处理Development状态的判断逻辑

修正后的实现代码

脚本部分(<script setup>)

import { computed } from 'vue'

// 模拟数据源
const dashboard = [
  {
    report: "Ad Hoc",
    description: "",
    status: "Production"
  }
];

// 计算属性:根据状态返回对应样式类
const reportStatus = computed(() => {
  const currentStatus = dashboard[0].status;
  switch(currentStatus) {
    case 'Production':
      return 'status--production';
    case 'Development':
      return 'status--development';
    default:
      return 'status--qa';
  }
});

模板部分

<div>
  <span 
    class="float-left text-center w-24 inline-block flex-shrink-0 rounded-full px-2 py-0.5 text-xs font-medium text-white inset-x-0 top-0" 
    :class="reportStatus"
  >
    {{ dashboard[0].status }}
  </span>
</div>

样式部分

.status--production {
  background-color: blue;
  color: white;
}

.status--development {
  background-color: #f59e0b; /* 自定义Development的背景色 */
  color: white;
}

.status--qa {
  background-color: green;
  color: white;
}

多数据列表场景适配

如果dashboard是多条数据的列表,用v-for遍历并通过方法动态获取样式类更灵活:

模板修改

<div v-for="item in dashboard" :key="item.report">
  <span 
    class="float-left text-center w-24 inline-block flex-shrink-0 rounded-full px-2 py-0.5 text-xs font-medium text-white inset-x-0 top-0" 
    :class="getStatusClass(item.status)"
  >
    {{ item.status }}
  </span>
</div>

脚本新增方法

// 动态生成样式类的方法
const getStatusClass = (status) => {
  if (status === 'Production') return 'status--production';
  if (status === 'Development') return 'status--development';
  return 'status--qa';
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:15:51