React中使用Vditor自定义图片详解


Posted in Javascript onDecember 25, 2020

安装

npm install vditor -s

引用

导入依赖包

import Vditor from "vditor";

导入样式

import "vditor/src/assets/scss/index.scss";

使用示例

export default class Vditor extends Component {
 constructor(props) {
   super(props);
   this.state = {
    editValue: ""
   };
 }
 componentDidMount = () => {
  //组件挂载完成之后调用 注意一定要在组件挂载完成之后调用 否则会找不到注入的DOM
  this.createVidtor({ value: this.state.editValue });
 }
 //创建编辑器 下面会详解
 createVidtor = params => {
   let { value } = params;
   value = value ? value : " ";
   let that = this;
   const vditor = new Vditor("vditor", {
     height: 800,
     mode: "ir", //及时渲染模式
     placeholder: "React Vditor",
     toolbar: [
       "emoji",
       "headings",
       "bold",
       "italic",
       "strike",
       "link",
       "|",
       "list",
       "ordered-list",
       "check",
       "outdent",
       "indent",
       "|",
       "quote",
       "line",
       "code",
       "inline-code",
       "insert-before",
       "insert-after",
       "|",
       "upload",
       "table",
       "|",
       "undo",
       "redo",
       "|",
       "fullscreen",
       "edit-mode",
       {
         name: "more",
         toolbar: [
           "both",
           "code-theme",
           "content-theme",
           "export",
           "outline",
           "preview",
           "devtools",
           "info",
           "help"
         ]
       },
       "|",
       {
         hotkey: "⌘-S",
         name: "save",
         tipPosition: "s",
         tip: "保存",
         className: "right",
         icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/save.svg'/>`,
         click() {
           that.saveDoc();
         }
       },
       {
         hotkey: "",
         name: "publish",
         tipPosition: "s",
         tip: "发布文章",
         className: "right",
         icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/publish.svg'/>`,
         click() {
           that.publishDoc();
         }
       }
     ],
     after() {
       vditor.setValue(value);
     },
     blur() {
       that.saveDoc();
     },
     upload: {
       accept: "image/*",
       multiple: false,
       filename(name) {
         return name
           .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
           .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
           .replace("/\\s/g", "");
       },
       handler(files) {
         function callback(path) {
           let name = files[0] && files[0].name;
           let succFileText = "";
           if (vditor && vditor.vditor.currentMode === "wysiwyg") {
             succFileText += `\n <img alt=${name} src="${path}">`;
           } else {
             succFileText += ` \n![${name}](${path})`;
           }
           document.execCommand("insertHTML", false, succFileText);
         }
         that.handleImageUpload(files, callback);
       },
       url(files) {
         that.handleImageUpload(files);
       }
     }
   });
   this.vditor = vditor;
   return vditor;
 };
 //首先需要在render里面注入DOM,可自定义注入DOM的ID,初始化编辑器的时候使用自定义的ID即可
 render() {
  <div className="editorWrap">
    <div id="vditor" />
  </div>
 }
}

示例:

React中使用Vditor自定义图片详解

功能使用

新建对象

const vditor = new Vditor("vditor", ...option);

新建对象时第一个参数ID,要对应上再render里面注入的ID

option参数

tip:只列举一下常用参数,其他的参数请参照 官方API

参数 说明
height 配置编辑器高度
mode 编辑器模式 wysiwyg:所见即所得2 ir:及时渲染 sv:分屏模式
placeholder 占位符
toolbar 工具栏

Tip:如果要自定义工具栏的话,一定要加上默认的工具栏,不然只展示自定义的了

默认工具栏

tip:此为源码里面copy 不用更改可直接使用,官方已定义好了快捷键和功能

toolbar: [
      "emoji",
      "headings",
      "bold",
      "italic",
      "strike",
      "link",
      "|",
      "list",
      "ordered-list",
      "check",
      "outdent",
      "indent",
      "|",
      "quote",
      "line",
      "code",
      "inline-code",
      "insert-before",
      "insert-after",
      "|",
      "upload",
      "record",
      "table",
      "|",
      "undo",
      "redo",
      "|",
      "fullscreen",
      "edit-mode",
      {
        name: "more",
        toolbar: [
          "both",
          "code-theme",
          "content-theme",
          "export",
          "outline",
          "preview",
          "devtools",
          "info",
          "help",
        ],
      }]

对应工具栏展示:

React中使用Vditor自定义图片详解

自定义按钮

let that = this;
const vditor = new Vditor("vditor", {
  toolbar: [
    {
      hotkey: "⌘-S",
      name: "save",
      tipPosition: "s",
      tip: "保存",
      className: "right",
      icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/save.svg'/>`,
      click() {
        that.saveDoc();
      }
    },
    {
      hotkey: "",
      name: "publish",
      tipPosition: "s",
      tip: "发布文章",
      className: "right",
      icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/publish.svg'/>`,
      click() {
        that.publishDoc();
      }
    }
  ]
});
//tip:在调用本类封装的方法时提前把this赋值给其他方法内的变量,在Vditor内部改变了this指向

参数 说明
hotkey 热键配置
name 功能区分(唯一性)
tip 悬浮提示
className UI展示 right靠右
icon 按钮图标
click 点击事件

示例:

React中使用Vditor自定义图片详解

获取值

saveDoc = () => {
 //在初始化时已经把vditor赋值到this对象上 可直接通过getValue方法获取当前编辑器的值
  let mdValue = this.vditor && this.vditor.getValue();
 //获取完值业务保存就行 这里不再详细写本人的保存方法了
 ...
}

赋值

let { value } = params;
value = value ? value : " ";
//如果是空值的话 最好给一个空格 以免编辑器初始化时报错
const vditor = new Vditor("vditor", {
 // value: value,
 after() {
   vditor.setValue(value);
 }
});
//tip:虽说官方也提供value直接赋值 但是在React里面不生效,就需要在after里面去调用setValue来完成赋值

自定义图片上传

const vditor = new Vditor("vditor", {
 upload: {
   accept: "image/*",
   multiple: false,
   filename(name) {
     return name
       .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
       .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
       .replace("/\\s/g", "");
   },
   handler(files) {
     function callback(path) {
       let name = files[0] && files[0].name;
       let succFileText = "";
       if (vditor && vditor.vditor.currentMode === "wysiwyg") {
         succFileText += `\n <img alt=${name} src="${path}">`;
       } else {
         succFileText += ` \n![${name}](${path})`;
       }
       document.execCommand("insertHTML", false, succFileText);
     }
     that.handleImageUpload(files, callback);
   },
   url(files, callback) {
     that.handleImageUpload(files, callback);
   }
 }
});
//此接口里面调用的是自己的图片上传 业务方自行实现
handleImageUpload = (file, callback) => {
  const reader = new FileReader();
  let formdata = new FormData();
  formdata.append("files", file[0]);
  reader.onload = () => {
    // setTimeout 模拟异步上传图片
    // 当异步上传获取图片地址后,执行callback回调(参数为imageUrl字符串),即可将图片地址写入markdown
    new Promise(resolve => {
      this.props.dispatch({
        type: "docManager/imageUpload",
        payload: { resolve, username: myInfo.userId, formdata }
      });
    }).then(res => {
      let imgurl = res.result.path;
      callback(imgurl);
    });
  };
  reader.readAsDataURL(file[0]);
};

参数 说明
accept 接收文件类型(我这边只做了图片上传)
multiple 是否多选
filename 格式化文件名
handler 点击数触发方法
url 配置此方法时可实现图片粘贴并上传

React中使用Vditor自定义图片详解

上传完成后接口返回的CDN地址

React中使用Vditor自定义图片详解

上传完成后处理

handler(files) {
  function callback(path) {
    let name = files[0] && files[0].name;
    let succFileText = "";
    //上传完成获取当前编辑器模式 根据不同模式拼接不同的展示标签
    if (vditor && vditor.vditor.currentMode === "wysiwyg") {
      succFileText += `\n <img alt=${name} src="${path}">`;
    } else {
      succFileText += ` \n![${name}](${path})`;
    }
    //拼接完直接插入到鼠标选中位置
    document.execCommand("insertHTML", false, succFileText);
  }
  that.handleImageUpload(files, callback);
}

React中使用Vditor自定义图片详解

总结

以上是本人在接入vditor编辑器是的一些使用总结,更多相关React Vditor内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Javascript 相关文章推荐
Extjs学习笔记之七 布局
Jan 08 Javascript
JavaScript对象学习经验整理
Oct 12 Javascript
Extjs中RowExpander控件的默认展开问题示例探讨
Jan 24 Javascript
javascript事件冒泡详解和捕获、阻止方法
Apr 12 Javascript
jquery实现Li滚动时滚动条自动添加样式的方法
Aug 10 Javascript
基于JQuery和CSS3实现仿Apple TV海报背景视觉差特效源码分享
Sep 21 Javascript
浅析JS操作DOM的一些常用方法
May 13 Javascript
用jmSlip编写移动端顶部日历选择控件
Oct 24 Javascript
JS实现图片放大缩小的方法
Feb 15 Javascript
npm全局模块卸载及默认安装目录修改方法
May 15 Javascript
详解Vue改变数组中对象的属性不重新渲染View的解决方案
Sep 21 Javascript
微信小程序实现的一键拨号功能示例
Apr 24 Javascript
基于vue+echarts数据可视化大屏展示的实现
Dec 25 #Vue.js
vue3使用vue-count-to组件的实现
Dec 25 #Vue.js
js+for循环实现字符串自动转义的代码(把后面的字符替换前面的字符)
Dec 24 #Javascript
Javascript 模拟mvc实现点餐程序案例详解
Dec 24 #Javascript
vant时间控件使用方法详解
Dec 24 #Javascript
基于Vant UI框架实现时间段选择器
Dec 24 #Javascript
原生jQuery实现只显示年份下拉框
Dec 24 #jQuery
You might like
使用URL传输SESSION信息
2015/07/14 PHP
php中简单的对称加密算法实现
2017/01/05 PHP
PHP后端银联支付及退款实例代码
2017/06/23 PHP
使用正则替换变量
2007/05/05 Javascript
JavaScript中使用正则匹配多条,且获取每条中的分组数据
2010/11/30 Javascript
jQuery验证Checkbox是否选中的代码 推荐
2011/09/04 Javascript
getAsDataURL在Firefox7.0下无法预览本地图片的解决方法
2013/11/15 Javascript
jQuery $.extend()用法总结
2014/06/15 Javascript
bootstrap实现动态进度条效果
2017/03/08 Javascript
整理关于Bootstrap模态弹出框的慕课笔记
2017/03/29 Javascript
vue2 自定义动态组件所遇到的问题
2017/06/08 Javascript
JavaScript中三个等号和两个等号你了解多少
2017/07/04 Javascript
JS设计模式之策略模式概念与用法分析
2018/02/05 Javascript
BootstrapValidator实现表单验证功能
2019/11/08 Javascript
python实现查找两个字符串中相同字符并输出的方法
2015/07/11 Python
一篇文章入门Python生态系统(Python新手入门指导)
2015/12/11 Python
python常用知识梳理(必看篇)
2017/03/23 Python
Python错误处理操作示例
2018/07/18 Python
详解Python用户登录接口的方法
2019/04/17 Python
python数据挖掘需要学的内容
2019/06/23 Python
python按修改时间顺序排列文件的实例代码
2019/07/25 Python
pygame实现俄罗斯方块游戏(基础篇3)
2019/10/29 Python
pycharm 对代码做静态检查操作
2020/06/09 Python
耐克美国官网:Nike.com
2016/08/01 全球购物
介绍一下grep命令的使用
2015/06/12 面试题
小学三八妇女节活动方案
2014/03/16 职场文书
单位法人授权委托书范本
2014/10/09 职场文书
教师群众路线心得体会
2014/11/04 职场文书
2015年挂职锻炼工作总结
2014/12/12 职场文书
2015年新教师工作总结
2015/04/28 职场文书
农业项目投资意向书
2015/05/09 职场文书
2015年化妆品销售工作总结
2015/05/11 职场文书
月考总结与反思
2015/10/22 职场文书
python实战之用emoji表情生成文字
2021/05/08 Python
python 开心网和豆瓣日记爬取的小爬虫
2021/05/29 Python
Oracle 触发器trigger使用案例
2022/02/24 Oracle