Vue中比较两个JSON对象的差异

2023-12-13 03:32:23

要在Vue.js中实现JSON数据的对比差异功能,你可以使用一些库来简化任务,比如diff-match-patch。以下是一个简单的例子,演示如何使用deep-diff库在Vue.js中比较两个JSON对象的差异:
首先,确保你的项目中已经安装了diff-match-patch库:

npm install diff-match-patch

然后,你可以在Vue组件中使用它:

<template>
  <div class="json-diff">
    <div class="side-by-side">
      <div class="left">
        <h3>Original JSON</h3>
        <pre>{{ prettyJson(jsonOriginal) }}</pre>
      </div>
      <div class="right">
        <h3>Modified JSON</h3>
        <pre>{{ prettyJson(jsonModified) }}</pre>
      </div>
    </div>
    <div class="diff-result">
      <h3>Difference</h3>
      <div v-html="diffHtml"></div>
    </div>
  </div>
</template>

<script>
import DiffMatchPatch from 'diff-match-patch';

export default {
  data() {
    return {
      jsonOriginal: {
        name: 'Jane',
        age: 25,
        city: 'New York',
      },
      jsonModified: {
        name: 'Jane',
        age: 26,
        city: 'Berlin',
        married: false,
      },
    };
  },
  computed: {
    diffHtml() {
      const dmp = new DiffMatchPatch();
      const diff = dmp.diff_main(
        this.prettyJson(this.jsonOriginal),
        this.prettyJson(this.jsonModified)
      );
      dmp.diff_cleanupSemantic(diff);
      return dmp.diff_prettyHtml(diff);
    },
  },
  methods: {
    prettyJson(json) {
      return JSON.stringify(json, null, 2);
    },
  },
};
</script>

<style scoped>
.json-diff {
  display: flex;
  flex-direction: column;
}

.side-by-side {
  display: flex;
  margin-bottom: 20px;
}

.left, .right {
  flex: 1;
}

.diff-result {
  background: #f8f8f8;
  padding: 20px;
}

/* 高亮样式 */
.diff {
  color: black;
}

.ins {
  background: #e6ffe6;
  text-decoration: none;
}

.del {
  background: #ffe6e6;
  text-decoration: none;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>

文章来源:https://blog.csdn.net/qq_35354529/article/details/134896916
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。