CodeMirror.MergeView

青春壹個敷衍的年華 提交于 2020-02-03 07:00:29

最近项目上需要实现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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!