安装两个关键插件
npm install diff-match-patch save
npm install codemirror@5.65.5 save
网上有很多相关教程,但是版本已不匹配,最终找到这个版本codemirror@5.65.5

<template>
  <div ref="codeMirror" class="code-contrast" style="width:100%;height:100%"></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: 'CodeMirror',
  props: {
    oldValue: {
      type: String,
      default: ''
    },
    newValue: {
      type: String,
      default: ''
    },
    isReadOnly: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
 
    }
  },
  watch: {
    oldValue: {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          this.initUI()
        })
      },
    },
    newValue: {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          this.initUI()
        })
      },
    }
  },
  methods: {
    initUI() {
      if (this.newValue == null) return;
      let target = this.$refs.codeMirror
      target.innerHTML = "";
      CodeMirror.MergeView(target, {
        value: this.oldValue,//上次内容
        origLeft: null,
        orig: this.newValue,//本次内容
        lineNumbers: true,//显示行号
        mode: "text/html",
        highlightDifferences: true,
        connect: 'align',
        readOnly: this.isReadOnly,//只读 不可修改
      });
    }
  },
}
</script>
<style lang="scss" scoped>
.code-contrast {
  .CodeMirror-merge-copy,
  .CodeMirror-merge-scrolllock-wrap {
    display: none !important;
  }
}
</style>

组件中调用

<template>
    <div>
      <code-mirror :oldValue="oldv" :newValue="newv"/>
    </div>
</template>
<script>
import CodeMirror from '....'  //路径代入
export default {
  components:{
    CodeMirror
  },
  data() {
    return {
      oldv:'旧文本',
      newv:'新文本',
    }
  }
}
</script>
GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐