4-wangeditor-自定义上传图片

314 阅读1分钟

vue3:wangeditor自定义上传图片

父组件

<template>
  <wang-editor @edit="getHtml"/>
</template>

<script>
export default {
  setUp() {
    // 获取图文详情
    const getHTML = (value) => {
      console.log(value);
    }
    
    return {
      getHTML
    }
  }
}
</script>

子组件

// => 子组件
<template>
  <div ref="xb_editor"></div>
</template>

<script>
import Editor from "wangeditor";
import { addProductPic } from "../../api/productApi.js";//上传文件得方法
import config from "../../config/index.js";//配置文件
import { onMounted, onBeforeUnMount, ref, reactive } from "vue";
export default {
  name: "Wangeditor",
  props: {
    height: {
      type: Number,
      default: 500
    }
  },
  emits: ["edit"],
  setup(props, ctx) {
    const editor = ref(null);
    //内容显示
    const content = reactive({
      html: "",
      text: "",
    });

    //创建单例对象
    let instance;
    onMounted(() => {
      instance = new Editor(editor.value);
      //配置高度
      instance.config.height = props.height;
      Object.assign(instance.config, {
        onChange(value) {
          //获取内容信息返回上级
          ctx.emit("edit", value);
        },
      });

      // 自定义图片上传
      instance.config.customUploadImg = async function (resultFiles, insertImgFn){
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后,插入到编辑器的方法
        let formData = new FormData();
        formData.append("file", resultFiles[0]);

        //调用上传接口
        const result = await addProductPic(formData);

        //获取返回过来得图片链接 并且插入
        if (result.status === 1) {
          insertImgFn(config.BASE_URL + result.data.name);
        }
      };
      //创建编辑器实例
      instance.create();
    });
};
</script>

配置项config

export default {
    KEY: 'zzz@#*09221``~~---++===yyyjhw',
    S_TOKEN: 's_token',
    S_USER: 's_user',
    BASE_URL: 'http://vue.xixixi.com:5000'
}