2022-05-16 15:54

VUE在线编辑器wangEditor安装使用

王姐姐

WEB前端

(1839)

(0)

收藏

1. 安装

官网:https://www.wangeditor.com/

vue2安装:npm install @wangeditor/editor-for-vue --save

vue3安装:npm install @wangeditor/editor-for-vue@next --save

2. 使用

2.1. 添加Toolbar标签和Editor标签

<el-form-item>
  <el-row>
    <el-col span="24">
  <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
  />
  <Editor
      style="height: 500px;border: 1px solid #ccc"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
  />
    </el-col>
  </el-row>
</el-form-item>

2.2. import

import '@wangeditor/editor/dist/css/style.css'
import { 
onBeforeUnmount
, 
ref
, 
shallowRef
, 
onMounted 
} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
//Vue3
的
setup
中不能用
this
引用全局变量,需要导入下面的
import { 
getCurrentInstance 
} from 'vue';

2.3. 指定组件

components: {Editor,Toolbar},

2.4. setup()方法

 setup() {
    // 编辑器实例,必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('')

    // 模拟 ajax 异步获取内容
    onMounted(() => {
/*      setTimeout(() => {
        valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
      }, 1500)*/

    })

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' ,MENU_CONF:{}}

    const baseURL =getCurrentInstance().appContext.config.globalProperties.baseURL
    console.log("===="+baseURL)
    //上传图片配置
    editorConfig.MENU_CONF['uploadImage'] = {
      server:baseURL+'manage/uploadPic',
      // form-data fieldName ,默认值 'wangeditor-uploaded-image'
      fieldName: 'picFile',

      // 单个文件的最大体积限制,默认为 2M
      maxFileSize: 1 * 1024 * 1024, // 1M

      // 最多可上传几个文件,默认为 100
      maxNumberOfFiles: 10,

      // 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
      allowedFileTypes: ['image/*'],

      // 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
      meta: {
        //token: window.sessionStorage.getItem('token')
      },

      // 将 meta 拼接到 url 参数中,默认 false
      metaWithUrl: false,

      // 自定义增加 http  header
      headers: {
        Accept: 'application/json',
        token: window.sessionStorage.getItem('token')
      },

      // 跨域是否传递 cookie ,默认为 false
      withCredentials: true,

      // 超时时间,默认为 10 秒
      timeout: 5 * 1000, // 5 秒
      // 上传之前触发
      onBeforeUpload(file) {
        // file 选中的文件,格式如 { key: file }
        return file

        // 可以 return
        // 1. return file 或者 new 一个 file ,接下来将上传
        // 2. return false ,不上传这个 file
      },
      // 上传进度的回调函数
      onProgress(progress) {
        // progress 是 0-100 的数字
        console.log('progress', progress)
      },
      // 单个文件上传成功之后
      onSuccess(file, res) {
        console.log(`${file.name} 上传成功`, res)
      },
      // 单个文件上传失败
      onFailed(file, res) {
        console.log(`${file.name} 上传失败`, res)
      },
      // 上传错误,或者触发 timeout 超时
      onError(file, err, res) {
        console.log(`${file.name} 上传出错`, err, res)
      },
    }

    // 组件销毁时,也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例,重要!
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated
    };
  },

2.5. 后台上传方法

//wangEditor上传成功的返回格式:
//
//{
//    "errno": 0, // 注意:值是数字,不能是字符串
//    "data": {
//        "url": "xxx", // 图片 src ,必须
//        "alt": "yyy", // 图片描述文字,非必须
//        "href": "zzz" // 图片的链接,非必须
//    }
//}
//上传失败的返回格式:
//
//{
//    "errno": 1, // 只要不等于 0 就行
//    "message": "失败信息"
//}
@PostMapping("/manage/uploadPic")
@ResponseBody
public JSONObject uploadPic(MultipartFile picFile,HttpServletRequest request){
    String fileName=null;
    if(picFile!=null&& !picFile.isEmpty()){
        try {
            //判断大小和类型
            //获得物理路径
            //String path = "D:\\uplaodImages";
            String path = ResourceUtils.getURL("classpath:").getPath()+"/static/uploadImages/";
            String ext = FilenameUtils.getExtension(picFile.getOriginalFilename());
            fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+ext;
            //保存图片
            picFile.transferTo(new File(path,fileName));

        } catch (IOException e) {
            e.printStackTrace();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("errno",1);
            jsonObject.put("message","wangEditor上传失败");
            return jsonObject;
        }
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("errno",0);
    JSONObject data = new JSONObject();
    data.put("url","http://localhost:8080/static/uploadImages/"+fileName);
    jsonObject.put("data",data);
    return jsonObject;
}

 


0条评论

点击登录参与评论