用法一:computed
<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
npm install diff
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;
});
用法二:封裝成方法
<div class="compareTableCss"><div v-for="cItem in compareTable" :key="cItem.line"><p>{{ cItem.title }}</p><p v-html="cItem.content"></p></div>
</div>
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);