vue2 使用wangeditor富文本编辑器组件 及 自定义上传图片

65 阅读1分钟

wangeditor富文本编辑器官网www.wangeditor.com/v5/for-fram…

  1. 安装依赖 ,可以通过以下命令来安装:
yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save

yarn add @wangeditor/editor-for-vue
# 或者 npm install @wangeditor/editor-for-vue --save
  1. 创建富文本编辑器组件 在Vue项目中,创建一个名为editorVue的组件,用于展示富文本编辑器界面和处理相关逻辑。
<template>
 <div style="border: 1px solid #ccc">
   <Toolbar
     style="border-bottom: 1px solid #ccc"
     :editor="editor"
     :defaultConfig="toolbarConfig"
     :mode="mode"
   />
   <Editor
     style="height: 350px; overflow-y: hidden"
     v-model="html"
     :defaultConfig="editorConfig"
     :mode="mode"
     @onChange="onChange"
     @onCreated="onCreated"
   />
 </div>
</template>
 <script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import base from "@/assets/js/base";
import axios from "axios";

export default {
 components: { Editor, Toolbar },
 props: {
   content: {
     type: String,
     default: "",
   },
 },
 data() {
   return {
     editor: null,
     html: "",
     toolbarConfig: {
       showLinkImg: false,
       uploadImgShowBase64: true,
       //不配置的项
       excludeKeys: [
         "insertVideo", // 删除视频
         "uploadVideo",
         "group-video",
         "insertTable", // 删除表格 
       ],
     },
     editorConfig: {
       placeholder: "请输入内容...",
       MENU_CONF: {
         // 配置上传图片
         uploadImage: {
           //自定义上传函数
           async customUpload(file, insertFn) {
             console.log(file, insertFn);
             let formdata = new FormData();
             formdata.append("file", file, file.name);
             // 图片上传
             axios({
               method: "post",
               url: base.url + 图片上传地址,
               data: formdata,
             }).then((res) => {
               console.log(res);
               if (res.status == 200) {
                 // 上传成功后返回图片预览路径地址
                 insertFn(base.url + res.data.obj[0].url);
               }
             });
           },
         },
       },
     },
     mode: "default", // 'default' or 'simple'
   };
 },
 methods: {
   onChange(editor) {
     this.$emit("changeData", this.html);
   },
   onCreated(editor) {
     this.editor = Object.seal(editor); // 一定要用 Object.seal() ,否则会报错
   },
 },
 created() {
   setTimeout(() => {
     this.html = this.content;
   }, 1200);
 },
 mounted() {},
 beforeDestroy() {
   const editor = this.editor;
   if (editor == null) return;
   editor.destroy(); // 组件销毁时,及时销毁编辑器
 },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>

3.引用组件

<editorVue
    v-if="detailVisible"
    :content="detailInfo.description"
    @changeData="editorChangeData"
/>

import editorVue from "@/components/editor.vue";

//获取到富文本编辑器的内容
editorChangeData(editDataHtml) {
    this.detailInfo.description = editDataHtml;
},