两段文本比对,高亮出差异部分

用法一:computed

html 复制代码
<div class="card" v-if="showFlag">
	<div class="info">*红色背景为已删除内容,绿色背景为新增内容</div>
	<el-form-item label="与上季度比对:">
		<div class="compareCss" v-html="highlightedLastQuarteDiff"></div>
	</el-form-item>
</div>

安装插件:diff

bash 复制代码
npm install diff
typescript 复制代码
import diff from 'diff';
// 与上季度比对
const highlightedLastQuarteDiff = computed(() => {
	const oldText = state.jsonContent ?? ''; // 旧值(原内容)
	const newText = state.content ?? ''; // 新值(修改后内容)

	const differences = diff.diffChars(oldText, newText); // 字符级差异对比
	let result = '';

	differences.forEach(part => {
		// 被删除的内容(旧值有,新值无)
		if (part.removed) {
			result += `<span style="text-decoration: line-through; background:#fbe9eb;color: red;  text-decoration-color: #777;">${part.value}</span>`;
		}
		// 新增的内容(旧值无,新值有)
		else if (part.added) {
			result += `<span style="background-color: #a6f3a6; color: #777;">${part.value}</span>`;
		}
		// 未改动的内容
		else {
			result += part.value;
		}
	});

	return result;
});

用法二:封装成方法

html 复制代码
<div class="compareTableCss">
	<div v-for="cItem in compareTable" :key="cItem.line">
		<p>{{ cItem.title }}</p>
		<p v-html="cItem.content"></p>
	</div>
</div>
javascript 复制代码
function highlightTextDifferences(oldText: string | null | undefined, newText: string | null | undefined): string {

	// 处理 null/undefined 情况
	const safeOldText = oldText ?? '';
	const safeNewText = newText ?? '';
	
	try {
		const differences = diff.diffChars(safeOldText, safeNewText);
		let result = '';
	
		differences.forEach((part:any) => {
			if (part.removed) {
				result += `<span style="text-decoration: line-through; background:#fbe9eb;color: red; text-decoration-color: #777;">${escapeHtml(part.value)}</span>`;
			} else if (part.added) {
				result += `<span style="background-color: #a6f3a6; color: #777;">${escapeHtml(part.value)}</span>`;
			} else {
				result += escapeHtml(part.value);
			}
		});
	
		return result;
	} catch (error) {
		console.error('Error in text comparison:', error);
		return escapeHtml(safeNewText); // 出错时返回新文本
	}
}
	
function escapeHtml(text: string): string {
	const div = document.createElement('div');
	div.textContent = text;
	return div.innerHTML;
}


// 使用
state.compareTable[1].content = highlightTextDifferences(fItem.windMuBiao, fItem.muBiao);
相关推荐
古希腊数通小白(ip在学)6 分钟前
HCIA实现不同vlan间的通信
linux·服务器·网络
半桔20 分钟前
【Linux手册】从接口到管理:Linux文件系统的核心操作指南
android·java·linux·开发语言·面试·系统架构
禁默28 分钟前
Linux Vim 编辑器详解:从入门到进阶(含图示+插件推荐)
linux·vim·excel
开开心心就好32 分钟前
电脑息屏工具,一键黑屏超方便
开发语言·javascript·电脑·scala·erlang·perl
江号软件分享33 分钟前
有效保障隐私,如何安全地擦除电脑上的敏感数据
前端
web守墓人2 小时前
【前端】ikun-markdown: 纯js实现markdown到富文本html的转换库
前端·javascript·html
Savior`L2 小时前
CSS知识复习5
前端·css
许白掰2 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
longze_76 小时前
Ubuntu连接不上网络问题(Network is unreachable)
linux·服务器·ubuntu
Dirschs6 小时前
【Ubuntu22.04安装ROS Noetic】
linux·ubuntu·ros