瀏覽代碼

fix: fix the error reported by the Editor component

陈凯龙 3 年之前
父節點
當前提交
90ef9856a0
共有 2 個文件被更改,包括 14 次插入6 次删除
  1. 1 1
      .vscode/settings.json
  2. 13 5
      src/components/Editor/src/Editor.vue

+ 1 - 1
.vscode/settings.json

@@ -5,7 +5,7 @@
     "source.fixAll.eslint": true
   },
   "[vue]": {
-    "editor.defaultFormatter": "johnsoncodehk.volar"
+    "editor.defaultFormatter": "rvest.vs-code-prettier-eslint"
   },
   "i18n-ally.localesPaths": ["src/locales"],
   "i18n-ally.keystyle": "nested",

+ 13 - 5
src/components/Editor/src/Editor.vue

@@ -1,6 +1,6 @@
 <script setup lang="ts">
-import { onBeforeUnmount, computed, PropType, unref, nextTick, ref, watch } from 'vue'
-import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'
+import { onBeforeUnmount, computed, PropType, unref, nextTick, ref, watch, shallowRef } from 'vue'
+import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
 import { IDomEditor, IEditorConfig, i18nChangeLanguage } from '@wangeditor/editor'
 import { propTypes } from '@/utils/propTypes'
 import { isNumber } from '@/utils/is'
@@ -23,6 +23,13 @@ const props = defineProps({
   defaultHtml: propTypes.string.def('')
 })
 
+// 编辑器实例,必须用 shallowRef
+const editorRef = shallowRef<IDomEditor>()
+
+const handleCreated = (editor: IDomEditor) => {
+  editorRef.value = editor
+}
+
 const emit = defineEmits(['change'])
 
 // 编辑器配置
@@ -70,17 +77,16 @@ const handleChange = (editor: IDomEditor) => {
 
 // 组件销毁时,及时销毁编辑器
 onBeforeUnmount(() => {
-  const editor = getEditor(props.editorId)
+  const editor = unref(editorRef.value)
   if (editor == null) return
 
   // 销毁,并移除 editor
   editor.destroy()
-  removeEditor(props.editorId)
 })
 
 const getEditorRef = async (): Promise<IDomEditor> => {
   await nextTick()
-  return getEditor(props.editorId) as IDomEditor
+  return unref(editorRef.value) as IDomEditor
 }
 
 defineExpose({
@@ -109,11 +115,13 @@ watch(
     />
     <!-- 编辑器 -->
     <Editor
+      :editor="editorRef"
       :editorId="editorId"
       :defaultConfig="editorConfig"
       :defaultHtml="defaultHtml"
       :style="editorStyle"
       @on-change="handleChange"
+      @onCreated="handleCreated"
     />
   </div>
 </template>