先上參考鏈接:https://www.cnblogs.com/lgx211/p/12720124.html
試了vue-json-code插件,效果不太理想, 改用vue-codemirror,查到很多使用方法,但是只需要對比的功能,具體實現(xiàn)步驟如下:
- 安裝依賴
npm i vue-codemirror
npm i diff-match-patch
- 引入 在這里我選擇的是局部引入
// 代碼對比插件
import CodeMirror from 'codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/merge/merge.js'
import 'codemirror/addon/merge/merge.css'
import DiffMatchPatch from 'diff-match-patch'
window.diff_match_patch = DiffMatchPatch
window.DIFF_DELETE = -1
window.DIFF_INSERT = 1
window.DIFF_EQUAL = 0
- HTML代碼 導入
<div id="view"></div>,實際使用如下:
<!-- 代碼版本,差異對比 對話框內(nèi)容 -->
<el-dialog title="差異對比" :visible.sync="editorDialog" class="history" width="60%">
<section class="box" >
<span>【注】左側(cè)為歷史版本,右側(cè)為當前版本</span>
<div id="view"></div>
</section>
</el-dialog>
- js內(nèi)容,其中
readOnly為true,代表僅展示,不可修改
// json對比
initUI (value, orig) {
if (value == null) return
const target = document.getElementById('view')
target.innerHTML = ''
CodeMirror.MergeView(target, {
value: value, // 上次內(nèi)容
origLeft: null,
orig: orig, // 本次內(nèi)容
lineNumbers: true, // 顯示行號
mode: '',
highlightDifferences: true,
foldGutter:true,
lineWrapping:true,
styleActiveLine: true,
matchBrackets: true,
connect: 'align',
readOnly: true // 只讀 不可修改
})
},
- 賦值,點擊第一個表格的歷史版本對比的按鈕時,獲取要對比的新舊值,調(diào)用 initUI()方法并傳入
/** 按鈕操作 */
editor () {
this.editorDialog = true
// 初始化版本差異
this.$nextTick(function () {
var a = this.oldStr // 舊版本
var b = this.newStr // 新版本
this.initUI(a,b)
})
},
-
效果圖,左側(cè)為歷史版本(舊),右側(cè)為當前版本(新),差異的部分會有波浪線。
image.png
