vue使用quill上传图片的基本配置我在前面文字中详细介绍过(https://segmentfault.com/a/11...)这里主要介绍上传图片,拖拽上传,截图粘贴,调整图片大小的使用。
一、下载安装
cnpm i vue-quill-editor -S
// 可拖拽图片
cnpm i quill-image-drop-module -S
// 这两个是改变图片大小的
cnpm i quill-image-resize-module -S
// 粘贴图片上传
cnpm i quill-image-paste-module -S
二、这些插件需要配置webpack支持,webpack.dev.conf.js/webpack.prod.conf.js
plugins: [
...
new webpack.ProvidePlugin({
'window.Quill': 'quill/dist/quill.js',
'Quill': 'quill/dist/quill.js'
})
...
三、配置组件,最好将富文本编辑器封装成公共组件使用
// 富文本编辑器 quill editor 样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import * as Quill from 'quill'
import { quillEditor } from 'vue-quill-editor'
// 拖拽上传
import { ImageDrop } from 'quill-image-drop-module'
// 调整上传图片大小
import ImageResize from 'quill-image-resize-module'
// 粘贴图片上传
import {ImageExtend} from 'quill-image-paste-module'
// 注册事件~~~~
Quill.register('modules/imageDrop', ImageDrop)
Quill.register('modules/imageResize', ImageResize)
Quill.register('modules/ImageExtend', ImageExtend)
// html文件
// 配置参数
editorOption: {
placeholder: this.placeholder ? this.placeholder : '请输入',
theme: 'snow',
modules: {
toolbar: {
container: toolbarOptions
},
// 拖拽上传
imageDrop: true,
// 调整图片大小
imageResize: {
displayStyles: {
backgroundColor: 'black',
border: 'none',
color: 'white'
},
modules: [ 'Resize', 'DisplaySize', 'Toolbar' ]
},
// 截屏上传
ImageExtend: {
loading: true,
name: 'file',
// 设置上传参数,因为我们要上传七牛,所以需要token
change: (xhr, FormData) => {
FormData.append('token', this.$store.state.upload_token)
},
action: 'https://upload.qiniup.com',
response: (res) => {
console.log(res, 'response')
// 这里有必要说一下,由于七牛上传成功以后返回的是 {hash: 'xxxx', key: 'xxx'},其中key就是七牛生成的文件名称,所以我们拼接上自己的服务器地址,就是图片保存的地址,return
的结果会座位图片的src
return this.$store.getters.upload_url + res.key
}
}
}
},
插件的具体配置可以查看:https://github.com/binperson/...
四、配置参数说明
modules: {
ImageExtend: { // 如果不作设置,即{} 则依然开启复制粘贴功能且以base64插入
name: 'img', // 图片参数名
size: 3, // 可选参数 图片大小,单位为M,1M = 1024kb
action: updateUrl, // 服务器地址, 如果action为空,则采用base64插入图片
// response 为一个函数用来获取服务器返回的具体图片地址
// 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
// 则 return res.data.url
response: (res) => {
return res.info
},
headers: (xhr) => {
// xhr.setRequestHeader('myHeader','myValue')
}, // 可选参数 设置请求头部
sizeError: () => {}, // 图片超过大小的回调
start: () => {}, // 可选参数 自定义开始上传触发事件
end: () => {}, // 可选参数 自定义上传结束触发的事件,无论成功或者失败
error: () => {}, // 可选参数 上传失败触发的事件
success: () => {}, // 可选参数 上传成功触发的事件
change: (xhr, formData) => {
// xhr.setRequestHeader('myHeader','myValue')
// formData.append('token', 'myToken')
} // 可选参数 每次选择图片触发,也可用来设置头部,但比headers多了一个参数,可设置formData
},
toolbar: { // 如果不上传图片到服务器,此处不必配置
container: container, // container为工具栏,此次引入了全部工具栏,也可自行配置
handlers: {
'image': function () { // 劫持原来的图片点击按钮事件
QuillWatch.emit(this.quill.id)
}
}
}
五、组件代码