<template>
  <div ref="editorRef" class="wang-editor"></div>
</template>
<script>
import WangEditor from "wangeditor";
import { uploadFile } from "@/api/public/public.js";
export default {
  name: "WangEditor",
  props: {
    value: {
      type: String,
      default: "",
    },
    // 编辑区域高度
    height: {
      type: Number | String,
      default: 200,
    },
    // placeholder
    placeholder: {
      type: String,
      default: "请输入",
    },
  },
  data() {
    return {
      editor: null,
      editorContent: this.value
    };
  },
  mounted() {
    document.getElementsByClassName("main-container")[0].classList.add("wang-editor-container");
    this.initEditor();
  },
  watch: {
    value(newVal) {
      this.editorContent = newVal;
    }
  },
  methods: {
    initEditor() {
      this.editor = new WangEditor(this.$refs.editorRef);

      this.initConfig();

      this.initCallback();

      this.editor.create();

      if (this.editorContent) {
        this.editor.txt.html(this.editorContent);
      }
    },
    // 初始化配置
    initConfig() {
      this.editor.config.height = parseInt(this.height);
      this.editor.config.placeholder = this.placeholder;
      this.editor.config.showLinkImg = false;
      this.configMenus();
      this.customAlert();
      this.customUploadImg();
    },
    initCallback() {
      this.editor.config.onchange = (newHtml) => {
        this.$emit("input", newHtml);
      };
    },
    configMenus() {
      this.editor.config.menus = ["bold", "image"];
    },
    customAlert() {
      this.editor.config.customAlert = (message, type) => {
        this.$message[type](message);
      };
    },
    customUploadImg() {
      this.editor.config.customUploadImg = async (resultFiles, insertImgFn) => {
        const imgUrl = await this.uploadImg(resultFiles[0]);
        insertImgFn(imgUrl);
      };
    },
    async uploadImg(file) {
      const formData = new FormData();
      formData.append("file", file);

      const { url } = await uploadFile(formData);
      return url;
    },
  },
  beforeDestroy() {
    // 销毁编辑器
    this.editor.destroy();
    this.editor = null;
    // 删除main-container下的wang-editor-container
    document.getElementsByClassName("main-container")[0].classList.remove("wang-editor-container");
  },
};
</script>
Vue 富文本组件 WangEditor 优化:解决 value 更新不触发内容变化问题

原文地址: https://www.cveoy.top/t/topic/pklp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录