基于Vue.js和Ant Design Vue實現(xiàn)根據(jù)字段內(nèi)容動態(tài)設(shè)置表格顏色功能
1. 需求分析
我們需要在表格中實現(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 組件庫:Ant Design Vue(
a-table
) - 輔助工具:
dayjs
(日期格式化)
3. 實現(xiàn)方案
3.1 使用 scopedSlots 自定義渲染
Ant Design Vue 的 a-table
提供了 scopedSlots
功能,允許我們自定義單元格的渲染方式。我們可以利用它來動態(tài)設(shè)置文字顏色。
關(guān)鍵代碼:
columns: [ { title: '安裝包列表數(shù)', dataIndex: 'appListCount', scopedSlots: { customRender: 'percentage' } // 使用自定義 slot } ]
3.2 動態(tài)計算顏色
在 Vue 的 methods
中定義一個方法 getPercentageColor
,根據(jù)字段內(nèi)容返回對應(yīng)的顏色。
基礎(chǔ)實現(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
中使用該方法動態(tài)綁定顏色:
<template slot="percentage" slot-scope="text"> <span :style="{ color: getPercentageColor(text) }">{{ text }}</span> </template>
4. 完整代碼實現(xiàn)
以下是完整的 Vue 組件代碼,包含表格、分頁、動態(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> <!-- 時間格式化 --> <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: '抓取時間', 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: { // 格式化時間 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'; }, // 動態(tài)計算百分比顏色 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'; }, // 分頁變化 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. 擴展優(yōu)化
5.1 支持更多格式
如果數(shù)據(jù)格式可能變化,例如 100%
不帶括號,可以調(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 實現(xiàn)表格字段的動態(tài)顏色渲染,核心要點包括:
- 使用
scopedSlots
自定義渲染,靈活控制單元格內(nèi)容。 - 動態(tài)計算顏色,通過字符串匹配或正則表達(dá)式判斷條件。
- 優(yōu)化健壯性,兼容不同數(shù)據(jù)格式(如帶/不帶括號的百分比)。
這種方法不僅適用于百分比數(shù)據(jù),還可以擴展至其他需要動態(tài)樣式的場景,如狀態(tài)標(biāo)簽、進度條等。
以上就是基于Vue.js和Ant Design Vue實現(xiàn)根據(jù)字段內(nèi)容動態(tài)設(shè)置表格顏色功能的詳細(xì)內(nèi)容,更多關(guān)于Vue.js字段內(nèi)容設(shè)置表格顏色的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Eclipse添加xml文件提示及Hibernate配置學(xué)習(xí)
文件提示功能在開發(fā)過程中很實用的,本文實現(xiàn)了一個Eclipse添加xml文件提示,感興趣的朋友可以了解下啊,希望本文對你有所幫助2013-01-01深入理解spring boot異步調(diào)用方式@Async
Spring為任務(wù)調(diào)度與異步方法執(zhí)行提供了注解支持。通過在方法上設(shè)置@Async注解,可使得方法被異步調(diào)用。下面這篇文章主要給大家介紹了關(guān)于spring boot異步調(diào)用方式@Async的相關(guān)資料,需要的朋友可以參考下。2017-07-07SpringBoot+Redis執(zhí)行l(wèi)ua腳本的5種方式總結(jié)
Lua是一種快速、輕量級的腳本語言,廣泛應(yīng)用于各種領(lǐng)域,包括數(shù)據(jù)庫,Redis作為一個內(nèi)嵌Lua解釋器的NoSQL數(shù)據(jù)庫,允許通過Lua腳本在服務(wù)器端執(zhí)行一些復(fù)雜的操作,本文給大家介紹了使用SpringBoot Redis執(zhí)行l(wèi)ua腳本的五種方式,需要的朋友可以參考下2023-11-11Java設(shè)計模式之狀態(tài)模式(State模式)介紹
這篇文章主要介紹了Java設(shè)計模式之狀態(tài)模式(State模式)介紹,本文講解了何時使用狀態(tài)模式、如何使用狀態(tài)模式等內(nèi)容,需要的朋友可以參考下2015-03-03