codeMirror在setValue后只有在聚焦的時候才會生效


參考鏈接
如果setTimeOut設置的值100不行,並且編輯器設置在dialog中,可以嘗試v-if來試試能否解決v-if="scriptEditorVisible",
改變字體大小可以通過setTimeOut來重新延遲刷新codemirror

<template>
  <div :style="wrapStyle">
    <textarea ref="mycode" v-model="code" @refresh="refreshValue"></textarea>
  </div>
</template>

<script>
import { iscriptString } from "../../assets/js/chartExample.js";
// 核心樣式
import "codemirror/lib/codemirror.css";
// 引入主題后還需要在 options 中指定主題才會生效

// 需要引入具體的語法高亮庫才會有對應的語法高亮效果
import "codemirror/mode/javascript/javascript.js";

// require active-line.js
import "codemirror/addon/selection/active-line.js";

let CodeMirror = require("codemirror/lib/codemirror");

export default {
  name: "codeMirror",
  data() {
    return {
      editor: null,
      options: {
        mode: "javascript",
        tabSize: 0, // 縮進格式
        lineNumbers: true, // 顯示行號
        autofocus: true, //初始化時自動獲取焦點
        autoRefresh: true,
      },
    };
  },
  methods: {
    // 獲取編輯器的值
    getEditor() {
      return this.editor.doc.getValue();
    },
    // 將值傳給父組件去更新
    setEditor() {
      this.$emit("setEditor", iscriptString(this.typeChart));
      return this.editor.doc.setValue(iscriptString(this.typeChart));
    },
    // 傳值進來設置
    setCodeEditor(val) {
      this.editor.doc.setValue(val);
      setTimeout(() => {
        this.editor.refresh();
      }, 100);
    },
    undo() {
      // 判斷是否與原來的代碼一致,一致就操作
      let chartCode = this.code;
      if (chartCode !== this.getEditor()) {
        this.editor.doc.undo();
      }
    },
    redo() {
      this.editor.doc.redo();
    },
    refresh() {
      // return this.editor.refresh();
      setTimeout(() => {
        this.editor.refresh();
      }, 1);
    },
    refreshValue() {
      alert();
    },

    _initEditor() {
      if (!this.editor) {
        this.editor = CodeMirror.fromTextArea(this.$refs.mycode, this.options);
      }
      this.editor.setValue(this.value || this.code);
      this.editor.setSize("auto", this.editorHeight);
    },
  },
  mounted() {
    this.$nextTick(() => {
      this._initEditor();
    });
  },
  watch: {
    code() {
      this.$nextTick(() => {
        this._initEditor();
      });
    },
    wrapStyle() {
      setTimeout(() => {
        this.refresh();
      }, 100);
    },
  },
  computed: {
    wrapStyle() {
      return { fontSize: this.fontSize + "px" };
    },
  },
  props: {
    fontSize: {
      type: String,
    },
    // 內部真實的內容
    code: {
      type: String,
      default: "",
    },
    // 圖表類型
    typeChart: {
      type: String,
      default: "",
    },
    // 腳本編輯器高度
    editorHeight: {
      type: String,
      default: "600px",
    },
  },
};
</script>

<style>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM