Selaa lähdekoodia

解决编辑器回显的问题

解决编辑器回显的问题
dangyunlong 1 viikko sitten
vanhempi
sitoutus
9f853d8674
2 muutettua tiedostoa jossa 31 lisäystä ja 4 poistoa
  1. 27 3
      src/components/edit/myEditor.vue
  2. 4 1
      src/views/news/creatNews.vue

+ 27 - 3
src/components/edit/myEditor.vue

@@ -1,16 +1,23 @@
 <template>
-  <tiny-editor v-model="content" :init="init" id="textarea"></tiny-editor>
+  <tiny-editor v-model="content" :init="init" :key="componentKey" id="textarea"></tiny-editor>
 </template>
 
 <script>
 import editor from '@tinymce/tinymce-vue';
 import url from '@/utils/baseUrl';
 
-
 export default {
   name: 'myEditor',
+  props: {
+    value: {
+      type: String,
+      default: ''
+    }
+  },
   data() {
     return {
+      editorInstance:{},
+      componentKey: 0, // 用于强制重新渲染
       content: '',
       init: {
         selector: '#textarea',
@@ -51,6 +58,10 @@ export default {
           xhr.send(formData);
         },
         setup: (editor) => {  // 这里改用箭头函数
+          // 存储编辑器引用
+          this.editorInstance = editor;
+          // 初始设置内容
+          editor.setContent(this.value);
           editor.on('change', () => {
             this.$emit('input', editor.getContent());  // 发送内容变化事件
           });
@@ -58,6 +69,16 @@ export default {
       }
     };
   },
+  watch: {
+    value(newVal) {
+      // 当父组件传入新内容时更新编辑器
+      if (this.editorInstance && newVal !== this.editorInstance.getContent()) {
+        this.content = newVal;
+        //以防万一可以使用下面这个方法 强制更新视图
+        //this.reinitEditor();
+      }
+    }
+  },
   components: {
       'tiny-editor': editor,
   },
@@ -65,7 +86,10 @@ export default {
 
   },
   methods: {
-
+    // 强制重新初始化编辑器(必要时使用)
+    reinitEditor() {
+      this.componentKey += 1;
+    }
   },
 }
 </script>

+ 4 - 1
src/views/news/creatNews.vue

@@ -766,7 +766,10 @@ export default {
         this.form.keyword = res.data.keyword;
         this.tags = res.data.keyword ? res.data.keyword.split(",") : [];
         this.form.introduce = res.data.introduce;
-        this.form.content = res.data.content;
+        //回显编辑器内容
+        this.$nextTick(() => {
+          this.form.content = res.data.content;
+        });
         this.form.author = res.data.author;
         this.form.hits = res.data.hits;
         this.form.is_original = res.data.is_original;