vue实现文本对比

本文档展示了如何在Vue组件中使用CodeMirror库的merge view功能,安装了特定版本的codemirror@5.65.5和diff-match-patch插件,以实现代码的差异对比和合并。组件接收oldValue和newValue作为输入,根据内容变化初始化编辑器,并提供了只读模式。在模板中引入组件并设置旧文本和新文本属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装两个关键插件
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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值