CodeEditor.vue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <template>
  2. <div style="height: 100%; width: 100%;"></div>
  3. </template>
  4. <script lang="ts">
  5. import Vue from 'vue'
  6. import * as Monaco from 'monaco-editor'
  7. import { editor } from 'monaco-editor'
  8. import ICodeEditor = editor.ICodeEditor
  9. import ITextModel = editor.ITextModel
  10. export default Vue.extend({
  11. name: 'CodeEditor',
  12. model: {
  13. event: 'change'
  14. },
  15. data() {
  16. return {
  17. editor: (null as unknown) as ICodeEditor,
  18. monaco: (null as unknown) as typeof Monaco
  19. }
  20. },
  21. props: {
  22. original: { default: '', type: String },
  23. value: {
  24. type: String,
  25. required: true
  26. },
  27. theme: {
  28. type: String,
  29. default: 'vs'
  30. },
  31. language: { default: '', type: String },
  32. options: {
  33. default: () => ({
  34. height: '100%'
  35. }),
  36. type: Object
  37. }
  38. },
  39. watch: {
  40. language: function(newVal) {
  41. if (this.editor) {
  42. const model = this.editor.getModel()
  43. this.monaco.editor.setModelLanguage(model as ITextModel, newVal)
  44. this.editor.setModel(model)
  45. }
  46. },
  47. value: function(newVal) {
  48. if (this.editor) {
  49. if (newVal !== this.editor.getValue()) {
  50. this.editor.setValue(newVal)
  51. }
  52. }
  53. }
  54. },
  55. mounted() {
  56. this.monaco = Monaco
  57. this.initMonaco()
  58. },
  59. beforeDestroy() {
  60. this.editor && this.editor.dispose()
  61. },
  62. methods: {
  63. initMonaco() {
  64. const options = {
  65. value: this.value,
  66. theme: this.theme,
  67. language: this.language,
  68. ...this.options
  69. }
  70. this.editor = this.monaco.editor.create(this.$el as HTMLElement, options)
  71. this.editor.onDidChangeModelContent((event) => {
  72. const value = this.editor.getValue()
  73. if (this.value !== value) {
  74. this.$emit('change', value)
  75. }
  76. })
  77. },
  78. setValue(val: string) {
  79. this.editor.setValue(val)
  80. }
  81. }
  82. })
  83. </script>
  84. <style></style>