学无先后,达者为师

网站首页 编程语言 正文

mocano editor中使用代码比对功能

作者:前端开心果 更新时间: 2023-07-29 编程语言

mocano editor中使用代码比对功能

环境:vue2.x + typescript

使用前提请先看:vue2.x中monaco-editor的基础使用

效果图:
在这里插入图片描述

创建代码公共组件

codeDiff.vue

<template>
  <div class="editor" :id="id"></div>
</template>

<script lang="ts">
import CodeDiff from "./codeDiff";
export default CodeDiff;
</script>

<style lang="less" scoped>
.editor {
  width: 100%;
  height: 635px;
  text-align: left;
}
</style>

codeDiff.ts

import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import * as Monaco from "monaco-editor";

interface ICode {
  value: string;
  language: string;
}

@Component
export default class CodeDiff extends Vue {
  diffInstance: any;
  id = "";

  @Prop({ default: { value: "", language: "" } })
  oldCode!: ICode;

  @Prop({ default: { value: "", language: "" } })
  code!: ICode;

  created(): void {
    this.id = `editor${Math.random()}`;
  }

  @Watch("oldCode", { deep: true })
  oldWatch(): void {
    this.change();
  }
  @Watch("code", { deep: true })
  nowWatch(): void {
    this.change();
  }

  mounted(): void {
    this.init();
  }
  setModel(instance: any): void {
    // 此处可以把`original`和`modified`按情况创建模型,比如初始两个都渲染,`original`
改变只创建`original`的model,`modified`改变只创建`modified`的model
	instance.setModel({
      original: Monaco.editor.createModel(
        this.oldCode.value,
        this.oldCode.language,
      ),
      modified: Monaco.editor.createModel(
        this.code.value,
        this.code.language,
      ),
    })
  }
  init(): void {
    const code: HTMLElement = document.getElementById(this.id) as HTMLElement;

    this.diffInstance = Monaco.editor.createDiffEditor(code, {
      wordWrap: "on",
      scrollBeyondLastLine: false,
      automaticLayout: true,
      readOnly: true,
    });
    this.setModel(this.diffInstance);
  }
  change(): void {
    if (this.diffInstance === null) {
      this.init();
      return;
    }
    this.setModel(this.diffInstance);
  }
}

使用组件

<code-diff :old-code="oldCodeInfo" :code="codeInfo" />

原文链接:https://blog.csdn.net/qq_38157825/article/details/124378219

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新