Search code examples
javascriptvue.jsvuejs2monaco-editor

Get values from Monaco Editor in Vue 2


I am new to Vuejs and have to integrate Vue2 with Monaco Editor. I want to get values input by user. I tried few ways but cannot get the value. Thanks in advance!

This is my Editor.vue file.

<template>
  <div id="editor" ref="editor"></div>
</template>

<script>
import * as monaco from "monaco-editor";

export default {
  name: "CodeEditor",
  mounted() {
    const editorOptions = {
      value: [
        "function greeting() {",
        '\tconsole.log("Test Monaco...);',
        "}",
      ].join("\n"),
      language: "text/javascript",
      minimap: { enabled: false },
      wordWrap: true,
      automaticLayout: true,
    };
    window.editor = monaco.editor.create(document.getElementById("editor"), editorOptions);
  },

  computed: {   
    getUserInput() {
      // how to get user input???
    },
  },
};
</script>

<style>
#editor {
  height: 500px;
  width: 100%;
  overflow: hidden;
}
</style>

Solution

  • It is very easy to get the value with the getValue() method that monaco editor has built-in.

        <template>
          <div id="editor" ref="editor"></div>
        </template>
        
        <script>
        import * as monaco from "monaco-editor";
        
        export default {
          name: "CodeEditor",
          data() {
              editor: null,
              editorOptions: {
                value: [ "function greeting() {", '\tconsole.log("Test Monaco...);', "}", ].join("\n"),
              language: "text/javascript",
              minimap: { enabled: false },
              wordWrap: true,
              automaticLayout: true
            }
          },
          methods: {
             createEditor() {
                this.editor = monaco.editor.create(document.getElementById("editor"), this.editorOptions);
             },
             getEditorValue() {
                // Returns the current editor value
                return this.editor.getValue()
             },
          },
          mounted() {
            this.createEditor()
          },
        };
        </script>
        
        <style>
        #editor {
          height: 500px;
          width: 100%;
          overflow: hidden;
        }
        </style>
    

    I set your variables in the data section and added a createEditor and getEditorValue method, they will help you to organize better your code.