前言
由于产品变更了需求,富文本要可插入表格(他咋不内嵌个word),而原来项目中的富文本插件(vue-quill-editor)并没有此功能,查看了网上的解决方案,大多数都选择了wangEditor,我这里用的是v4版本。
遇到的坑
- 插入本地视频后,光标问题不能移动到最后(不过现在好像最新的v4版本已经解决了此问题)
- 至于其他的问题目前都可以在配置中找到相应的api,也可以在下边留言,大家一起讨论
基本使用
安装:npm i wangeditor --save
<template>
<div class="home">
<h3>wangEditor with vue</h3>
<div id="editer"></div>
</div>
</template>
<script>
// 引入 wangEditor
import wangEditor from 'wangeditor'
export default {
data() {
return {
editor: null,
editorData: ''
}
},
mounted() {
const editor = new wangEditor(`#demo1`)
// 配置 onchange 回调函数,将数据同步到 vue 中
editor.config.onchange = (newHtml) => {
this.editorData = newHtml
}
// 创建编辑器
editor.create()
this.editor = editor
},
methods: {
},
beforeDestroy() {
// 调用销毁 API 对当前编辑器实例进行销毁
this.editor.destroy()
this.editor = null
}
}
</script>
<style lang="scss">
.home {
width: 1200px;
margin: auto;
position: relative;
}
</style>
配置视频上传(图片上传类似)
mounted () {
const _this = this
const editor = new wangEditor(`#editer`)
// 配置 onchange 回调函数,将数据同步到 vue 中
editor.config.onchange = (newHtml) => {
this.form.productDetails = newHtml
}
editor.config.menus = [
'fontName', // 字体
'fontSize', // 字号
'foreColor', // 字体颜色
'backColor', // 背景色
'underline', // 下划线
'italic', // 斜体
'bold', // 加粗
'justify', // 对齐方式
'splitLine', // 分割线
'undo', // 撤销
'redo', // 恢复
'list', // 列表(有序、无序)
'table', // 表格
'image', // 图片
'video', // 视频
...
]
// 配置服务器基础路径
editor.config.uploadVideoServer = '/oss/files'
// 最大文件限制 5M
editor.config.uploadVideoMaxSize = 5 * 1024 * 1024
// 类型限制
editor.config.uploadVideoAccept = ['mp4']
// 上传文件规定字段
editor.config.uploadVideoName = 'file'
// 上传超时限制
editor.config.uploadVideoTimeout = 60000
// 替换报错提醒用 element-ui 的样式
editor.config.customAlert = function (s, t) {
switch (t) {
case 'success':
_this.$message.success(s)
break
case 'info':
_this.$message.info(s)
break
case 'warning':
_this.$message.warning(s)
break
case 'error':
_this.$message.error(s)
break
default:
_this.$message.info(s)
break
}
}
// 占用符配置
editor.config.placeholder = '请输入商品详情'
...
// 创建编辑器
editor.create()
this.editor = editor
},
配置解决视频上传光标不能移动到视频后问题
正常情况下用:insertVideoFn(url) ,但是遇到上述问题,所以更改为手动创建
video标签,并在前后拼接 ,最后再插入富文本中
...
editor.config.uploadVideoHooks = {
...
// 视频上传并返回了结果,想要自己把视频插入到编辑器中customInsert
customInsert: function(insertVideoFn, result) {
// result 即服务端返回的接口
// insertVideoFn 可把视频插入到编辑器,传入视频 src ,执行函数即可
let videoHTML = ' <video src="' + result.redirect_uri + '" controls style="max-width:100%"></video> ';
editor.cmd.do('insertHTML', videoHTML);
}
}
...