vue-codemirror代碼差異對比的使用

先上參考鏈接: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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容