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

用法一: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);
相关推荐
小小小小宇2 小时前
虚拟列表兼容老DOM操作
前端
悦悦子a啊2 小时前
Python之--基本知识
开发语言·前端·python
2401_826097623 小时前
JavaEE-Linux环境部署
java·linux·java-ee
安全系统学习3 小时前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss
涛哥码咖4 小时前
chrome安装AXURE插件后无效
前端·chrome·axure
OEC小胖胖4 小时前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
(:满天星:)4 小时前
第31篇:块设备与字符设备管理深度解析(基于OpenEuler 24.03)
linux·运维·服务器·网络·centos
行云&流水4 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
爱莉希雅&&&4 小时前
shell编程之awk命令详解
linux·服务器·git
笑稀了的野生俊4 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力