mocano editor中使用代码比对功能

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" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值