用代码怎么实现呢,非只读的情况
const { editor } = ref.current; 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,
// 只读状态下无法生效
如果需求是只读的情况怎么处理
/ 方案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 = `\n${ele}`; } else if (j % 2 === 0 && ele === '{') { ele += '\n'; // eslint-disable-next-line no-plusplus k++; for (ii = 0; ii < k; ii++) ele += ' '; } else if (j % 2 === 0 && ele === ',') { ele += '\n'; 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