开发文档
配置项
方法配置

方法配置

用于配置 Umo Editor 的方法,包括文档保存方法、文件上传方法、文件删除方法等。

默认方法

{
  async onSave(content, page, document) {
    throw new Error('Key "onSave": Please set the save method')
  },
  async onFileUpload(file) {
    if (!file) throw new Error('File not found')
    throw new Error('Key "onFileUpload": Please set the upload method')
  },
  onFileDelete(id, url) {
    console.error(
      'The file has been deleted. Please configure the onFileDelete to completely delete the file from the server.',
    )
  },
}

配置项说明

onSave

说明:配置文档保存方法,在用户保存文档时,调用此方法,将文档保存到服务器。

类型:异步函数或 Promise。

参数

  • content:文档内容。
  • page:页面信息。
  • document:文档信息。

返回值:保存成功则返回 true,否则返回 false,否则返回 false 或者抛出错误

示例

以下代码以 Axios 为例,演示如何配置 onSave 方法,将文档保存到服务器:

import axios from 'axios';
import { useUmoEditor } from '@umoteam/editor';
 
const options = {
  async onSave(content, page, document) => {
    const res = await axios.post('/api/save', {
      content,
      page,
      document,
    },{
      headers: {
        'Content-Type': 'application/json',
      }
    });
 
    // 保存成功则返回 true,否则返回 false,否则返回 false 或者抛出错误
    return true; 
  },
};
 
app.use(useUmoEditor, options);

onFileUpload

说明:配置文件上传方法,用户插入文件时,会触发该方法,将文件上传到服务器。

类型:异步函数或 Promise。

参数

  • file:File 对象。

返回值

  • id:上传成功后返回的文件 id。
  • url:上传成功后返回的文件 url。

示例

以下代码以 Axios 为例,演示如何配置 onFileUpload 方法,将文件上传到服务器:

import axios from 'axios';
import { useUmoEditor } from '@umoteam/editor';
 
const options = {
  async onFileUpload(file) => {
    let formData = new FormData();
    // 添加文件到 formData 对象中
    formData.append('file', file);
    const res = await axios.post('/api/file-upload', formData,{
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    });
 
    // 保存成功则返回 {id, url},否则返回 false 或者抛出错误
    return {
      id: res.data.id,
      url: res.data.url,
    }; 
  },
};
 
app.use(useUmoEditor, options);

onFileDelete

说明:配置文件删除方法,用户删除文件时,会触发该方法,将文件从服务器上删除。

类型:函数。

参数

  • id:文件 id。
  • url:文件 url。

示例

以下代码以 Axios 为例,演示如何配置 onFileDelete 方法,将文件从服务器上删除:

import axios from 'axios';
import { useUmoEditor } from '@umoteam/editor';
 
const options = {
  onFileDelete(id, url) => {
    axios.delete(`/api/file/${id}`);
  },
};
 
app.use(useUmoEditor, options);