vue实现文本对比

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

<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>

你可能感兴趣的:(vue文本对比,vue.js,javascript,前端)