wuyuedefeng / blogs

博客文章在issue中
5 stars 0 forks source link

vue 实现文本差异对比diff #129

Open wuyuedefeng opened 2 years ago

wuyuedefeng commented 2 years ago

diff两个文本对比,并展示到页面,类似github上的代码修改记录

使用到的库:

实现

<template>
    <div class="text-diff" ref="rootRef" v-html="prettyHtml"></div>
</template>

<script lang='jsx'>
import { reactive, toRefs, defineComponent, computed } from 'vue'
import { createPatch } from 'diff'
import * as Diff2Html from 'diff2html'
import 'diff2html/bundles/css/diff2html.min.css'

export default defineComponent({
    props: {
        // 通过两个文本,计算diffText
        compareTexts: {
            type: Array,
            default: () => []
        },
        // 直接传diffText, 类似git diff得到的结果
        diffText: [String]
    },
    setup (props, ctx) {
        const state = reactive({
            prettyHtml: computed(() => {
                let diffText = props.diffText
                                // 如果传递的是两个文本则对比两个文本得到diff描述
                if (props.compareTexts) {
                    const [firstValue = '', secondValue = ''] = props.compareTexts
                    diffText = createPatch('diff', firstValue, secondValue)
                }
                const outputHtml = Diff2Html.html(diffText, {
                    drawFileList: false,
                    matching: 'lines',
                    inputFormat: "diff",
                    outputFormat: 'side-by-side',
                })
                return outputHtml
            })
        })
        return { ...toRefs(state) }
    },
})
</script>

<style lang="scss" scoped>
</style>