vue实现文件对比
Vue实现文件对比的方法
使用第三方库实现差异对比
推荐使用diff-match-patch或jsdiff库,它们专为文本差异对比设计,支持高亮显示差异部分。安装后可直接在Vue组件中调用。

npm install diff-match-patch
<template>
<div>
<textarea v-model="oldText"></textarea>
<textarea v-model="newText"></textarea>
<button @click="compare">对比</button>
<div v-html="diffResult"></div>
</div>
</template>
<script>
import { diff_match_patch } from 'diff-match-patch';
export default {
data() {
return {
oldText: '',
newText: '',
diffResult: ''
}
},
methods: {
compare() {
const dmp = new diff_match_patch();
const diffs = dmp.diff_main(this.oldText, this.newText);
dmp.diff_cleanupSemantic(diffs);
this.diffResult = dmp.diff_prettyHtml(diffs);
}
}
}
</script>
自定义对比算法实现
对于简单需求可编写基础对比逻辑,通过遍历字符数组标记差异点。

<template>
<div>
<div v-for="(line, index) in diffLines" :key="index"
:style="{ color: line.type === 'added' ? 'green' : line.type === 'removed' ? 'red' : 'black' }">
{{ line.text }}
</div>
</div>
</template>
<script>
export default {
props: ['oldText', 'newText'],
computed: {
diffLines() {
const oldLines = this.oldText.split('\n');
const newLines = this.newText.split('\n');
const result = [];
const maxLength = Math.max(oldLines.length, newLines.length);
for (let i = 0; i < maxLength; i++) {
if (oldLines[i] !== newLines[i]) {
if (oldLines[i]) result.push({ type: 'removed', text: `- ${oldLines[i]}` });
if (newLines[i]) result.push({ type: 'added', text: `+ ${newLines[i]}` });
} else {
result.push({ type: 'unchanged', text: ` ${oldLines[i] || newLines[i]}` });
}
}
return result;
}
}
}
</script>
文件上传对比实现
结合文件输入和FileReader API,可扩展为上传文件对比功能。
<template>
<div>
<input type="file" @change="handleFile(0, $event)" />
<input type="file" @change="handleFile(1, $event)" />
<button @click="compareFiles">对比文件</button>
<div v-html="diffResult"></div>
</div>
</template>
<script>
import { diff_match_patch } from 'diff-match-patch';
export default {
data() {
return {
files: ['', ''],
diffResult: ''
}
},
methods: {
handleFile(index, event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = e => this.files[index] = e.target.result;
reader.readAsText(file);
},
compareFiles() {
const dmp = new diff_match_patch();
const diffs = dmp.diff_main(this.files[0], this.files[1]);
this.diffResult = dmp.diff_prettyHtml(diffs);
}
}
}
</script>
可视化差异高亮组件
使用vue-diff等现成组件可快速实现专业对比界面,支持行号显示和多种主题。
npm install vue-diff
<template>
<vue-diff :old-string="oldText" :new-string="newText" />
</template>
<script>
import { VueDiff } from 'vue-diff';
export default {
components: { VueDiff },
data() {
return {
oldText: '旧文本内容',
newText: '新文本内容'
}
}
}
</script>






