版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
wangEditor是一款优秀的国产编辑器。
轻量级 web 富文本编辑器,配置方便,使用简单。支持 IE10+ 浏览器。
但是自身带的图片上传在上传七牛云可能存在版本问题。还有如果是其他云的JS上传图片的话就爱莫能助了,好在wangEditor提供了丰富的API可以换一种思路来实现。
1:使用提供的API 接口:
editor.customConfig.customUploadImg = function (files, insert) {
// files 是 input 中选中的文件列表
// insert 是获取图片 url 后,插入到编辑器的方法
// 上传代码返回结果之后,将图片插入到编辑器中
insert(imgUrl)
}
这里可以拦截到上传前的图片信息然后调用自己的上传文件方法,最后,插入到编辑器中,
2:取巧,自定义图标上传图片:
文末粘贴全部代码
- 编辑器外层封一层DIV,
- 添加一个图标(真正上传需要图标里隐藏添加一个input用来选择文件,这里不写了,麻烦)
- CSS绝对定位
- 给图标添加点击事件,实现上传逻辑
<div class="top-div">
<span class="el-icon-picture uploadimg" @click="uploadimg"></span>
<div ref="editor" style="text-align:left"></div>
</div>
这里代码很简单。我们只是多添加了两组元素
编写样式:
<style scoped>
.top-div{
position: relative;
width: 50%;
margin: 0 auto;
}
.uploadimg{
position: absolute;
color: rgb(153,153,153);
font-size: 20px;
top: 6px;
left: 159px;
}
</style>
然后就简单了。直接给图标绑定上传事件:
<span class="el-icon-picture uploadimg" @click="uploadimg"></span>
然后在事件中(此处打开资源管理器选择图片,进行上传忽略)图片上传完成后获取到图片的URL即可。
uploadimg(){
// do something 这里用js上传完成之后获取到图片地址
let url = "http://119.254.155.37:8080/img/home/zhenwutu%402x.png"
// 调用编辑器api插入图片
this.editor.cmd.do('insertHTML', '<img src="'+url+'" alt="" width="100px" height="200px">')
}
全部代码:
<template>
<div class="top-div">
<span class="el-icon-picture uploadimg" @click="uploadimg"></span>
<div ref="editor" style="text-align:left"></div>
</div>
</template>
<script>
import E from 'wangeditor'
export default {
name: "appEditArt",
data() {
return {
editor: null,
}
},
mounted() {
this.seteditor();
},
methods: {
seteditor() {
this.editor = new E(this.$refs.editor);
this.editor.customConfig.menus = [
'head',
'bold',
'italic',
'underline'
]
// 创建富文本编辑器
this.editor.create()
},
uploadimg(){
// do something 这里用js上传完成之后获取到图片地址
let url = "http://119.254.155.37:8080/img/home/zhenwutu%402x.png"
// 调用编辑器api插入图片
this.editor.cmd.do('insertHTML', '<img src="'+url+'" alt="" width="100px" height="200px">')
}
},
}
</script>
<style scoped>
.top-div{
position: relative;
width: 50%;
margin: 0 auto;
}
.uploadimg{
position: absolute;
color: rgb(153,153,153);
font-size: 20px;
top: 6px;
left: 159px;
}
</style>