基于CodeMirror和diff-match-patch封装一个vue中的文本对比组件

如上图

项目中需要对比文本修改前后不同的差异之处.

考虑到方便后期复用,便封装成一个components组件

首先装包

cnpm install diff-match-patch save
cnpm install codemirror save
<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="less">
.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 kvpFormMixin from '@/mixins/KvpFormMixin'
import CodeMirror from '@/components/CodeMirror'

export default {
  components:{
    CodeMirror
  },
  data() {
    return {
      // TODO 模拟数据,请更换
      oldv:'旧文本',
      newv:'新文本',
    }
  }
}
</script>

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值