一、需求:旧字符串 str1 ,改成新字符串 str2 ,两个字符串不同的地方高亮显示
三、具体步骤:
1、安装
npm install diff-match-patch
2、具体文件进行使用
<template>
<div id="app">
<div>
旧文本:<div>dog1s bark</div>
新文本:<div>cat12s bark</div>
</div>
</div>
</template>
<script>
import DiffMatchPatch from 'diff-match-patch';
export default {
mounted(){
const dmp = new DiffMatchPatch();
const diff = dmp.diff_main('dog1s bark', 'cat12s bark')
var div = document.createElement('div')
diff.forEach(function (item) {
var span = document.createElement('span')
span.innerText = item[1]
// 删除
if(item[0] === -1){
span.style.textDecoration = 'line-through'
span.style.background = '#ffe6e6'
}
// 插入
if(item[0] === 1){
span.style.textDecoration = 'underline'
span.style.background = '#e6ffe6'
}
div.appendChild(span)
})
document.body.appendChild(div)
}
}
</script>
3、最终效果如下: