基于Vue.js和Ant Design Vue實(shí)現(xiàn)根據(jù)字段內(nèi)容動(dòng)態(tài)設(shè)置表格顏色功能
1. 需求分析
我們需要在表格中實(shí)現(xiàn)以下效果:
- 如果字段內(nèi)容包含
(100%),則文字顯示為 綠色(表示成功或完成)。 - 如果字段內(nèi)容包含
(0%),則文字顯示為 紅色(表示失敗或未完成)。 - 其他情況顯示為 橙色(表示部分成功或中間狀態(tài))。
示例數(shù)據(jù):
7 (100%) → 綠色 0 (0%) → 紅色 5 (50%) → 橙色
2. 技術(shù)選型
- 前端框架:Vue.js(2.x / 3.x 均適用)
- UI 組件庫(kù):Ant Design Vue(
a-table) - 輔助工具:
dayjs(日期格式化)
3. 實(shí)現(xiàn)方案
3.1 使用 scopedSlots 自定義渲染
Ant Design Vue 的 a-table 提供了 scopedSlots 功能,允許我們自定義單元格的渲染方式。我們可以利用它來(lái)動(dòng)態(tài)設(shè)置文字顏色。
關(guān)鍵代碼:
columns: [
{
title: '安裝包列表數(shù)',
dataIndex: 'appListCount',
scopedSlots: { customRender: 'percentage' } // 使用自定義 slot
}
]
3.2 動(dòng)態(tài)計(jì)算顏色
在 Vue 的 methods 中定義一個(gè)方法 getPercentageColor,根據(jù)字段內(nèi)容返回對(duì)應(yīng)的顏色。
基礎(chǔ)實(shí)現(xiàn):
methods: {
getPercentageColor(value) {
if (value.includes('(100%)')) return 'green';
if (value.includes('(0%)')) return 'red';
return 'orange';
}
}
優(yōu)化版本(更健壯的匹配):
getPercentageColor(value) {
if (typeof value !== 'string') return 'orange'; // 非字符串默認(rèn)橙色
// 使用正則匹配,兼容可能的空格或格式變化
if (/\(\s*100\s*%\)/.test(value)) return 'green';
if (/\(\s*0\s*%\)/.test(value)) return 'red';
return 'orange';
}
3.3 在模板中應(yīng)用樣式
在 a-table 的 template 中使用該方法動(dòng)態(tài)綁定顏色:
<template slot="percentage" slot-scope="text">
<span :style="{ color: getPercentageColor(text) }">{{ text }}</span>
</template>
4. 完整代碼實(shí)現(xiàn)
以下是完整的 Vue 組件代碼,包含表格、分頁(yè)、動(dòng)態(tài)顏色等功能:
<template>
<a-modal
title="抓取記錄"
:visible="visible"
width="90%"
@cancel="handleCancel"
:destroyOnClose="true"
>
<a-table
rowKey="id"
:columns="columns"
:dataSource="data"
:pagination="pagination"
:loading="loading"
@change="handleTableChange"
bordered
>
<!-- 狀態(tài)列 -->
<template slot="graspingStatus" slot-scope="text">
<a-tag :color="getStatusColor(text)">
{{ getStatusText(text) }}
</a-tag>
</template>
<!-- 時(shí)間格式化 -->
<template slot="time" slot-scope="text">
{{ formatDateTime(text) }}
</template>
<!-- 百分比列顏色控制 -->
<template slot="percentage" slot-scope="text">
<span :style="{ color: getPercentageColor(text) }">{{ text }}</span>
</template>
</a-table>
</a-modal>
</template>
<script>
import dayjs from 'dayjs';
import { getGraspingRecords } from '@/api/ad-api/media';
export default {
name: 'GraspingRecordModal',
data() {
return {
loading: false,
data: [],
pagination: {
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
pageSizeOptions: ['10', '20', '50', '100'],
showTotal: total => `共 ${total} 條記錄`
},
columns: [
{ title: '任務(wù)ID', dataIndex: 'graspingTaskId' },
{ title: '總?cè)罩緮?shù)', dataIndex: 'totalCount' },
{
title: '狀態(tài)',
dataIndex: 'graspingStatus',
scopedSlots: { customRender: 'graspingStatus' }
},
{
title: '抓取時(shí)間',
dataIndex: 'graspingTime',
scopedSlots: { customRender: 'time' }
},
{
title: '設(shè)備ID數(shù)',
dataIndex: 'deviceIdCount',
scopedSlots: { customRender: 'percentage' }
},
// 其他列...
]
};
},
props: {
visible: { type: Boolean, default: false },
mediaAdId: { type: [Number, String], required: true }
},
watch: {
visible(val) {
if (val) {
this.pagination.current = 1;
this.fetchData();
} else {
this.data = [];
this.pagination.total = 0;
}
}
},
methods: {
// 格式化時(shí)間
formatDateTime(timeStr) {
return timeStr ? dayjs(timeStr).format('YYYY-MM-DD HH:mm:ss') : '-';
},
// 狀態(tài)文本
getStatusText(status) {
const map = { 0: '失敗', 1: '成功', 2: '部分成功' };
return map[status] || '未知';
},
// 狀態(tài)顏色
getStatusColor(status) {
const map = { 0: 'red', 1: 'green', 2: 'orange' };
return map[status] || 'default';
},
// 動(dòng)態(tài)計(jì)算百分比顏色
getPercentageColor(value) {
if (typeof value !== 'string') return 'orange';
if (/\(\s*100\s*%\)/.test(value)) return 'green';
if (/\(\s*0\s*%\)/.test(value)) return 'red';
return 'orange';
},
// 分頁(yè)變化
handleTableChange(pagination) {
this.pagination.current = pagination.current;
this.pagination.pageSize = pagination.pageSize;
this.fetchData();
},
// 獲取數(shù)據(jù)
async fetchData() {
this.loading = true;
try {
const { data: res } = await getGraspingRecords({
mediaAdId: this.mediaAdId,
page: this.pagination.current,
pageSize: this.pagination.pageSize
});
if (res.code === '000000') {
this.data = res.data.aaData || [];
this.pagination.total = res.data.iTotalRecords || 0;
} else {
throw new Error(res.msg || '獲取數(shù)據(jù)失敗');
}
} catch (error) {
console.error('獲取抓取記錄失敗:', error);
this.$message.error(error.message);
this.data = [];
this.pagination.total = 0;
} finally {
this.loading = false;
}
},
// 關(guān)閉模態(tài)框
handleCancel() {
this.$emit('close');
}
}
};
</script>
<style scoped>
/* 可自定義樣式 */
</style>
5. 擴(kuò)展優(yōu)化
5.1 支持更多格式
如果數(shù)據(jù)格式可能變化,例如 100% 不帶括號(hào),可以調(diào)整正則:
getPercentageColor(value) {
if (typeof value !== 'string') return 'orange';
if (/(\(\s*100\s*%\)|100%)/.test(value)) return 'green';
if (/(\(\s*0\s*%\)|0%)/.test(value)) return 'red';
return 'orange';
}
5.2 使用 CSS 類代替行內(nèi)樣式
<template slot="percentage" slot-scope="text">
<span :class="getPercentageClass(text)">{{ text }}</span>
</template>
<style>
.green-text { color: green; }
.red-text { color: red; }
.orange-text { color: orange; }
</style>
getPercentageClass(value) {
if (typeof value !== 'string') return 'orange-text';
if (/\(\s*100\s*%\)/.test(value)) return 'green-text';
if (/\(\s*0\s*%\)/.test(value)) return 'red-text';
return 'orange-text';
}
6. 總結(jié)
本文介紹了如何基于 Vue.js 和 Ant Design Vue 實(shí)現(xiàn)表格字段的動(dòng)態(tài)顏色渲染,核心要點(diǎn)包括:
- 使用
scopedSlots自定義渲染,靈活控制單元格內(nèi)容。 - 動(dòng)態(tài)計(jì)算顏色,通過(guò)字符串匹配或正則表達(dá)式判斷條件。
- 優(yōu)化健壯性,兼容不同數(shù)據(jù)格式(如帶/不帶括號(hào)的百分比)。
這種方法不僅適用于百分比數(shù)據(jù),還可以擴(kuò)展至其他需要?jiǎng)討B(tài)樣式的場(chǎng)景,如狀態(tài)標(biāo)簽、進(jìn)度條等。
以上就是基于Vue.js和Ant Design Vue實(shí)現(xiàn)根據(jù)字段內(nèi)容動(dòng)態(tài)設(shè)置表格顏色功能的詳細(xì)內(nèi)容,更多關(guān)于Vue.js字段內(nèi)容設(shè)置表格顏色的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java?Stream?的?Collectors.toMap高級(jí)應(yīng)用與最佳實(shí)踐
文章講解Java?Stream?API中Collectors.toMap的使用,涵蓋基礎(chǔ)語(yǔ)法、鍵沖突處理、自定義Map類型、null值安全、復(fù)雜值轉(zhuǎn)換及性能優(yōu)化等場(chǎng)景,本文將從基礎(chǔ)用法入手,逐步深入探討其高級(jí)應(yīng)用與最佳實(shí)踐,感興趣的朋友一起看看吧2025-08-08
java解決動(dòng)態(tài)配置字段需求問(wèn)題
這篇文章主要介紹了java解決動(dòng)態(tài)配置字段需求問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
java 根據(jù)坐標(biāo)截取圖片實(shí)例代碼
這篇文章主要介紹了java 根據(jù)坐標(biāo)截取圖片實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-03-03
Spring中@RequestParam與@RequestBody的使用場(chǎng)景詳解
這篇文章主要介紹了Spring中@RequestParam與@RequestBody的使用場(chǎng)景詳解,注解@RequestParam接收的參數(shù)是來(lái)自requestHeader中即請(qǐng)求頭或body請(qǐng)求體,通常用于GET請(qǐng)求,比如常見(jiàn)的url等,需要的朋友可以參考下2023-12-12
springboot對(duì)接第三方微信授權(quán)及獲取用戶的頭像和昵稱等等
這篇文章主要介紹了springboot對(duì)接第三方微信授權(quán)及獲取用戶的頭像和昵稱等等,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01

