vue:diff库实现文本对比
- 安装diff库
npm install diff
- 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>
- js
不支持import 语法,module引入
const Diff = require('diff');
数据定义
data () {
return {
resultStr: '',
oldStr: `时光静寂,岁月轻柔,~~这是要删除的文本~~拈一颗素心,轻倚季节的转角,
看流年的风轻轻吹过,始终相信,时光可以带走最美的年华,岁月可以刻画老去的颜容,
但那些过往的中的莹亮,那些光阴浸染的情怀,终是停留在记忆深处,
明媚了岁月,芬芳了生命。`,
newStr: `时光静寂,岁月轻柔,拈一颗素心,轻倚季节的转角,
看流年的风轻轻吹过,~~~~~~~这是新增的文本~~~~~~始终相信,时光可以带走最美的年华,岁月可以刻画老去的颜容,
但那些过往的中的莹亮,那些光阴浸染的情怀,终是停留在记忆深处,
明媚了岁月,芬芳了生命。`
}
},
数据处理
const d = Diff.diffChars(this.oldStr, this.newStr)
this.resultStr = d
- css
.remove {
color: red;
background-color: #fee8e9;
text-decoration: line-through;
}
.add {
color: green;
background-color: #ddffdd;
}
.default {
color: grey;
}


浙公网安备 33010602011771号