zoukankan      html  css  js  c++  java
  • MonacoEditor编辑器自动格式代码

    MonacoEditor代码编辑器怎么实现自动格式化代码功能?

    1.界面上右键下边截图的这个Format Document点击一下就好了

    2.用代码怎么实现呢,非只读的情况

    // 写法1
    const { editor } = ref.current;
    editor.setValue('这里写要待格式化的数据');
    editor.trigger('anyString', 'editor.action.formatDocument');//自动格式化代码
    editor.setValue(editor.getValue());//再次设置
    // 写法2
    const { editor } = ref.current;
    editor.setValue('这里写要待格式化的数据');
    editor.getAction('editor.action.formatDocument').run();//自动格式化代码
    editor.setValue(editor.getValue());//再次设置
    //写法不同目的是一样的,上面那个自动格式化代码的操作,就是上边方法截图的那个
    // 这个写法需要注意的情况是
      // MonacoEditord的配置只能是:readOnly: false,
     // 只读状态下无法生效

    3.如果需求是只读的情况怎么处理

    // 方案1:
    // readOnly: true的情况
    // setValue前先把数据自己处理一下
    const { editor } = ref.current;
    editor.setValue(checkJsonCode('待格式化的数据'));
    export function checkJsonCode(strJsonCode) {
      let res = '';
      try {
        for (let i = 0, j = 0, k = 0, ii, ele; i < strJsonCode.length; i++) {
          ele = strJsonCode.charAt(i);
          if (j % 2 === 0 && ele === '}') {
            // eslint-disable-next-line no-plusplus
            k--;
            for (ii = 0; ii < k; ii++) ele = `    ${ele}`;
            ele = `
    ${ele}`;
          } else if (j % 2 === 0 && ele === '{') {
            ele += '
    ';
            // eslint-disable-next-line no-plusplus
            k++;
            for (ii = 0; ii < k; ii++) ele += '    ';
          } else if (j % 2 === 0 && ele === ',') {
            ele += '
    ';
            for (ii = 0; ii < k; ii++) ele += '    ';
            // eslint-disable-next-line no-plusplus
          } else if (ele === '"') j++;
          res += ele;
        }
      } catch (error) {
        res = strJsonCode;
      }
      return res;
    }
     // 方案2:
    那就用一个div来当做遮罩层覆盖编辑功能,然后把改成
    readOnly:false
    
    
  • 相关阅读:
    shell 编写简单的整数计算器
    信号控制
    MySQL-索引及优化整理
    Java面试-Java容器有哪些
    C语言宏定义
    值类型与引用类型的区别
    C++虚函数简介
    DNS-域名解析
    扇区,簇,块区分
    Java合并两个数组为一个新数组
  • 原文地址:https://www.cnblogs.com/ChineseLiao/p/15214921.html
Copyright © 2011-2022 走看看