vue实现文本对比
Vue 实现文本对比功能
文本对比功能可以通过比较两个文本内容的差异,并以可视化的方式展示差异部分。以下是几种实现方式:
使用 diff-match-patch 库
diff-match-patch 是一个高效的文本差异比较库,可以轻松集成到 Vue 项目中。
安装 diff-match-patch:
npm install diff-match-patch
在 Vue 组件中使用:
<template>
<div>
<textarea v-model="text1" placeholder="文本1"></textarea>
<textarea v-model="text2" placeholder="文本2"></textarea>
<button @click="compareTexts">比较文本</button>
<div v-html="diffResult"></div>
</div>
</template>
<script>
import { diff_match_patch } from 'diff-match-patch';
export default {
data() {
return {
text1: '',
text2: '',
diffResult: ''
};
},
methods: {
compareTexts() {
const dmp = new diff_match_patch();
const diffs = dmp.diff_main(this.text1, this.text2);
dmp.diff_cleanupSemantic(diffs);
this.diffResult = this.formatDiff(diffs);
},
formatDiff(diffs) {
return diffs.map(([type, text]) => {
if (type === -1) return `<del style="color:red">${text}</del>`;
if (type === 1) return `<ins style="color:green">${text}</ins>`;
return text;
}).join('');
}
}
};
</script>
使用 vue-diff 组件
vue-diff 是一个专门为 Vue 开发的文本对比组件。
安装 vue-diff:
npm install vue-diff
使用示例:
<template>
<div>
<vue-diff :old-string="text1" :new-string="text2" />
</div>
</template>
<script>
import VueDiff from 'vue-diff';
import 'vue-diff/dist/index.css';
export default {
components: { VueDiff },
data() {
return {
text1: '旧文本内容',
text2: '新文本内容'
};
}
};
</script>
自定义实现简单文本对比
对于简单的文本对比需求,可以自己实现基本的差异比较:
<template>
<div>
<div class="comparison">
<div class="text-container">
<div v-for="(line, index) in lines1" :key="'text1-' + index">
<span :class="{ 'diff': line !== lines2[index] }">{{ line }}</span>
</div>
</div>
<div class="text-container">
<div v-for="(line, index) in lines2" :key="'text2-' + index">
<span :class="{ 'diff': line !== lines1[index] }">{{ line }}</span>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
text1: '第一行\n第二行\n第三行',
text2: '第一行\n修改行\n第三行'
};
},
computed: {
lines1() {
return this.text1.split('\n');
},
lines2() {
return this.text2.split('\n');
}
}
};
</script>
<style>
.comparison {
display: flex;
}
.text-container {
width: 50%;
padding: 10px;
}
.diff {
background-color: #ffcccc;
}
</style>
使用 Monaco Editor 实现代码对比
对于代码对比,可以使用 Monaco Editor(VS Code 使用的编辑器):
<template>
<div id="container" style="width:800px;height:600px"></div>
</template>
<script>
import * as monaco from 'monaco-editor';
export default {
mounted() {
const originalModel = monaco.editor.createModel(
'function hello() {\n console.log("Hello");\n}',
'javascript'
);
const modifiedModel = monaco.editor.createModel(
'function hello() {\n console.log("Hello World");\n}',
'javascript'
);
const diffEditor = monaco.editor.createDiffEditor(
document.getElementById('container'),
{
readOnly: true,
automaticLayout: true
}
);
diffEditor.setModel({
original: originalModel,
modified: modifiedModel
});
}
};
</script>
以上方法可以根据具体需求选择适合的实现方式,从简单的文本差异到专业的代码对比都能满足不同场景的需求。






