先上参考链接:https://www.cnblogs.com/lgx211/p/12720124.html
试了vue-json-code插件,效果不太理想, 改用vue-codemirror,查到很多使用方法,但是只需要对比的功能,具体实现步骤如下:
- 安装依赖
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>
,实际使用如下:
<!-- 代码版本,差异对比 对话框内容 -->
<el-dialog title="差异对比" :visible.sync="editorDialog" class="history" width="60%">
<section class="box" >
<span>【注】左侧为历史版本,右侧为当前版本</span>
<div id="view"></div>
</section>
</el-dialog>
- js内容,其中
readOnly
为true,代表仅展示,不可修改
// json对比
initUI (value, orig) {
if (value == null) return
const target = document.getElementById('view')
target.innerHTML = ''
CodeMirror.MergeView(target, {
value: value, // 上次内容
origLeft: null,
orig: orig, // 本次内容
lineNumbers: true, // 显示行号
mode: '',
highlightDifferences: true,
foldGutter:true,
lineWrapping:true,
styleActiveLine: true,
matchBrackets: true,
connect: 'align',
readOnly: true // 只读 不可修改
})
},
- 赋值,点击第一个表格的历史版本对比的按钮时,获取要对比的新旧值,调用 initUI()方法并传入
/** 按钮操作 */
editor () {
this.editorDialog = true
// 初始化版本差异
this.$nextTick(function () {
var a = this.oldStr // 旧版本
var b = this.newStr // 新版本
this.initUI(a,b)
})
},
-
效果图,左侧为历史版本(旧),右侧为当前版本(新),差异的部分会有波浪线。