一、需求
最近开发一个审核功能,详情编辑以后,
在原列表查看,详情是旧数据,
在审核中心查看,修改过的数据要显示新数据并且高亮
二、实现思路
初步思考,决定通过自定义指令
实现颜色的高亮和数据的替换
比在代码中、直接通过判断添加样式和写三元表达式精简
后端再给一个接口,传递修改过的数据
三、代码实现
(1)自定义指令的代码实现如下
ts
import { createApp } from 'vue'
const DEFAULT_COLOR: Record<string, any> = {
blue: '#409EFF',
// red: '',
}
export default {
install(app: ReturnType<typeof createApp>): void {
app.directive('highlight', (el, binding) => {
const { open, currentValue, newValue, replace } = binding.value || {}
if (!open) return // 如果不需要高亮,直接返回
if (
(currentValue != null && currentValue !== newValue)
|| (currentValue == null && binding.oldValue !== newValue)
) {
el.style.color = binding.arg ? DEFAULT_COLOR[binding.arg] : DEFAULT_COLOR.blue
} else {
el.style.color = 'inherit'
}
// 替换内容
if (replace) {
el.textContent = newValue ?? ''
}
})
},
}
页面表格代码实现如下
js
<el-table-column
prop="couponDate"
align="center"
min-width="110px"
label="日期">
<template #default="scope">
<span>{{ scope.row.couponDate }}</span>
</template>
</el-table-column>
<el-table-column
prop="couponAmount"
align="center"
min-width="170px"
label="金额">
<template #default="scope">
<span v-highlight:blue="{ open: reviewData.updateType === 2, newValue: reviewData.couponInfo?.[scope.$index]?.couponAmount, replace: true }">{{ scope.row.couponAmount }}</span>
</template>
</el-table-column>
查看页面效果,金额前面没给高亮的日期列,数据也高亮了,其他列正常,真是奇怪!!

三、问题初步解决
1、认真查看代码及其逻辑,未发现什么问题,
2、是不是代码里有全局的css样式,检查以后排除,
3、在给el-table加上row-key,也无济于事,
4、在日期的span上加上样式 style="color: inherit", 依然不起作用,
还有其他尝试,依然没效果,
最后,在认真思考一下,本列通过自定义指令改了颜色,
影响了它前面一列的颜色,会不会是它找不到准确元素或者element plus内部相关css属性
尝试给span元素在包裹一层,问题还真解决了
js
<el-table-column
prop="couponDate"
align="center"
min-width="110px"
label="日期">
<template #default="scope">
<span>{{ scope.row.couponDate }}</span>
</template>
</el-table-column>
<el-table-column
prop="couponAmount"
align="center"
min-width="170px"
label="金额">
<template #default="scope">
<span>
<span v-highlight:blue="{ open: reviewData.updateType === 2, newValue: reviewData.couponInfo?.[scope.$index]?.couponAmount, replace: true }">{{ scope.row.couponAmount }}</span>
</span>
</template>
</span>el-table-column>
深层原因暂未去寻,在此简单记录一下