index.hook.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { ref, onBeforeUnmount, nextTick } from 'vue'
  2. import { useDesignStore } from '@/store/modules/designStore/designStore'
  3. import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js'
  4. export const useMonacoEditor = (language = 'javascript') => {
  5. const designStore = useDesignStore()
  6. let monacoEditor: monaco.editor.IStandaloneCodeEditor | null = null
  7. let initReadOnly = false
  8. const el = ref<HTMLElement | null>(null)
  9. // 格式化
  10. const onFormatDoc = async () => {
  11. await monacoEditor?.getAction('monacoEditor.action.formatDocument')?.run()
  12. }
  13. // 更新
  14. const updateVal = (val: string) => {
  15. nextTick(async () => {
  16. monacoEditor?.setValue(val)
  17. initReadOnly && monacoEditor?.updateOptions({ readOnly: false })
  18. await onFormatDoc()
  19. initReadOnly && monacoEditor?.updateOptions({ readOnly: true })
  20. })
  21. }
  22. // 创建实例
  23. const createEditor = (editorOption: monaco.editor.IStandaloneEditorConstructionOptions = {}) => {
  24. if (!el.value) return
  25. const javascriptModel = monaco.editor.createModel('', language)
  26. initReadOnly = !!editorOption.readOnly
  27. // 创建
  28. monacoEditor = monaco.editor.create(el.value, {
  29. model: javascriptModel,
  30. // 是否启用预览图
  31. minimap: { enabled: false },
  32. // 圆角
  33. roundedSelection: true,
  34. // 主题
  35. theme: designStore.getDarkTheme ? 'vs-dark' : 'vs',
  36. // 主键
  37. multiCursorModifier: 'ctrlCmd',
  38. // 滚动条
  39. scrollbar: {
  40. verticalScrollbarSize: 8,
  41. horizontalScrollbarSize: 8
  42. },
  43. // 行号
  44. lineNumbers: 'off',
  45. // tab大小
  46. tabSize: 2,
  47. //字体大小
  48. fontSize: 16,
  49. // 控制编辑器在用户键入、粘贴、移动或缩进行时是否应自动调整缩进
  50. autoIndent: 'advanced',
  51. // 自动布局
  52. automaticLayout: true,
  53. ...editorOption
  54. })
  55. return monacoEditor
  56. }
  57. // 卸载
  58. onBeforeUnmount(() => {
  59. if (monacoEditor) monacoEditor.dispose()
  60. })
  61. return {
  62. el,
  63. updateVal,
  64. getEditor: () => monacoEditor,
  65. createEditor,
  66. onFormatDoc
  67. }
  68. }