简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM