最近项目上需要实现2个文本的比较展示功能,找了一圈发现CodeMirror.MergeView
自带这个功能,其实里面用的diff插件是Google的diff-match-patch
,在github的星星还蛮多,就用选择这个插件了。
下面写个demo以便备忘。
安装依赖
npm install codemirror
npm install diff-match-patch
完整代码
<template>
<div id="view"></div>
</template>
<script>
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
export default {
name: 'Diff',
mounted () {
let value = 'abcc'
let orig2 = 'abcd'
this.initUI(value, orig2)
},
methods: {
initUI (value, orig2) {
if (value == null) {
return
}
let target = document.getElementById('view')
target.innerHTML = ''
CodeMirror.MergeView(target, {
value: value, // 上次内容
origLeft: null,
orig: orig2, // 本次内容
lineNumbers: true, // 显示行号
mode: 'text/html',
highlightDifferences: true,
connect: 'align',
revertButtons: true, // 是否显示还原按钮
readOnly: true// 只读 不可修改
})
}
}
}
</script>
<style scoped>
</style>
最终效果
工程代码:https://github.com/clj198606061111/vue_itclj_demo/blob/master/src/components/Diff.vue