vue:diff库实现文本对比

  1. 安装diff库
npm install diff
  1. html
<template>
  <div>
    <div style="white-space: pre-line">
      <span
        v-for="(item,index) in resultStr"
        :key="index"
        :class="item.added?'add':item.removed?'remove':'default'"
      >{{item.value}}</span>
    </div>
  </div>
</template>
  1. js
    不支持import 语法,module引入
const Diff = require('diff');

数据定义

data () {
    return {
      resultStr: '',
      oldStr: `时光静寂,岁月轻柔,~~这是要删除的文本~~拈一颗素心,轻倚季节的转角,
      看流年的风轻轻吹过,始终相信,时光可以带走最美的年华,岁月可以刻画老去的颜容,
      但那些过往的中的莹亮,那些光阴浸染的情怀,终是停留在记忆深处,
      明媚了岁月,芬芳了生命。`,
      newStr: `时光静寂,岁月轻柔,拈一颗素心,轻倚季节的转角,
      看流年的风轻轻吹过,~~~~~~~这是新增的文本~~~~~~始终相信,时光可以带走最美的年华,岁月可以刻画老去的颜容,
      但那些过往的中的莹亮,那些光阴浸染的情怀,终是停留在记忆深处,
      明媚了岁月,芬芳了生命。`
    }
  },

数据处理

const d = Diff.diffChars(this.oldStr, this.newStr)
this.resultStr = d
  1. css
.remove {
  color: red;
  background-color: #fee8e9;
  text-decoration: line-through;
}
.add {
  color: green;
  background-color: #ddffdd;
}
.default {
  color: grey;
}
  1. 效果图

    6.参考文档
    https://www.jianshu.com/p/6b8db8b979b3
    官方文档:https://www.npmjs.com/package/diff
posted @ 2022-06-25 10:59  年轻浅识  阅读(1171)  评论(0)    收藏  举报