1. 程式人生 > 實用技巧 >富文字編輯器 | wangeditor

富文字編輯器 | wangeditor

wangeditor 大家一般用的比較多,是一款很簡介的富文字編輯器,今天使用的時候,遇到了一些問題,分享給大家,避免踩坑。
一般我們使用時,都會把富文字編輯器抽成一個元件,然後其他介面呼叫,下面分享編輯器元件程式碼。
<template>
  <div ref="editor" />
</template>
<script>

  import E from 'wangeditor'

  export default {
    name: "TaRichEditor",
    props: {
      // 相容之前的配置寫法
      customConfig: {
        type: Object,
        default() {
          return {}
        },
      },
      // wangeditor2 版本的配置為config
      config: {
        type: Object,
        default() {
          return {}
        },
      },
      content: {
        type: String,
        default() {
          return ''
        },
      },
      disabled: {
        type: Boolean,
        default: () => false,
      },
    },
    data() {
      return {
        editor: {},
      }
    },
    watch: {
      disabled(val) {
        this.setDisabled(val)
      },
      content(val) {
        this.setContent(val)
      }
    },
    mounted() {
      let editor = new E(this.$refs.editor);
      editor.config = Object.assign(editor.config,this.config,this.customConfig)
      editor.create();
      this.editor = editor
    },
    methods: {
      setDisabled(val) {
        if (val) {
          this.editor.disable()
        } else {
          this.editor.enable()
        }
      },
      //獲取內容(html格式)
      getHtml() {
        return this.editor.txt.html();
      },
      //獲取內容(文字格式)
      getText() {
        return this.editor.txt.text();
      },
      //設定內容
      setContent(content) {
        if (!this.disabled) {
          this.editor.txt.html(content);
        }
      },
      //追加內容
      appendContent(content) {
        if (!this.disabled) {
          this.editor.txt.append(content);
        }
      },
      //清空內容
      clearContent() {
        if (!this.disabled) {
          this.editor.clear();
        }
      },
    },
  }
</script>

<style scoped>
  .w-e-toolbar{
    flex-wrap:wrap;
  }
</style>

其他介面呼叫程式碼如下
<wangEditor ref="richEditor" :content="content"></wangEditor>
問題出現在初始化賦值的時候,會一直為空。原因是我們獲取資料時,是非同步操作,然後富文字編輯器建立時,值仍然是為空。
解決辦法有兩種:
1、像我程式碼中那樣,監聽content的值,然後變化時進行設定。
2、在呼叫介面獲取到值之後,進行設值覆蓋。
這兩種辦法我覺得都行,只是第一個可以不用再關注設值問題,第二個還要注意給富文字設值。