本文首发于个人博客 Cyy’s Blog
转载请注明出处 https://cyyjs.top/blog/5b45dbd8e8d2af6195ec52f5

后端提供上传文件接口/upload

# 编写上传代码

editor增加属性ref="editor"@imgAdd="imgAdd"事件:
引入vuexmapAction,提供saveImg方法:

    async imgAdd(filename, imgfile) {
      // 上传成功返回URL地址
      let url = await this.saveImg(imgfile);
      if (url) {
       // 替换编辑器中的地址
        this.$refs.editor.$img2Url(filename, url);
      }
    }

vuex代码:

import Config from "../../../config";
import Axios from "axios";
const API_URL = Config.API_URL;
Axios.defaults.baseURL = API_URL;

const actions = {
  // 保存上传图片
  async saveImg(v, file) {
    let formdata = new FormData();
    formdata.append("file", file);
    let {
      data: {
        data: { url }
      }
    } = await Axios({
      url: "upload",
      method: "post",
      data: formdata,
      headers: { "Content-Type": "application/x-www-form-urlencoded" }
    });
    return url;
  }
}
export default {
  actions
};