富文本编辑vue-quill-editor文件上传
富文本自定义插入a链接
import Quill from 'quill';
import { quillEditor } from 'vue-quill-editor';
// 自定义插入a链接
var Link = Quill.import('formats/link');
class FileBlot extends Link { // 继承Link Blot
static create(value) {
let node = undefined
if (value&&!value.href){ // 适应原本的Link Blot
node = super.create(value);
}
else{ // 自定义Link Blot
node = super.create(value.href);
// node.setAttribute('download', value.innerText); // 左键点击即下载
node.innerText = value.innerText;
node.download = value.innerText;
}
return node;
}
}
FileBlot.blotName = 'link';
FileBlot.tagName = 'A';
Quill.register(FileBlot);
配置工具栏,添加了一个upload,其余不需要的都可以去掉
<script>
// 自定义插入a链接
// ...
// 工具栏配置
const toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{'header': 1}, {'header': 2}], // custom button values
[{'list': 'ordered'}, {'list': 'bullet'}],
[{'script': 'sub'}, {'script': 'super'}], // superscript/subscript
[{'indent': '-1'}, {'indent': '+1'}], // outdent/indent
[{'direction': 'rtl'}], // text direction
[{'size': ['small', false, 'large', 'huge']}], // custom dropdown
[{'header': [1, 2, 3, 4, 5, 6, false]}],
[{'color': []}, {'background': []}], // dropdown with defaults from theme
[{'font': []}],
[{'align': []}],
['link', 'image', 'upload'],
['clean'] // remove formatting button
]
export default {
data () {
return {
content: '',
editorOption: {
modules: {
toolbar: {
container: toolbarOptions, // 工具栏
handlers: {
'upload': ((value) => {
if (value) {
alert('自定义文件上传')
}
})
}
}
}
}
}
}
}
</script>
自定义文件上传的图标样式
.ql-snow.ql-toolbar .ql-upload{
background: url("../../assets/images/icon-upload.svg");
background-size: 16px 16px;
background-position: center center;
background-repeat:no-repeat;
/*background: red;*/
}
调用element上传组件
<!-- 上传文件 -->
<Upload :show-upload-list="false"
:on-success="handleFileSuccess"
:before-upload="handleFileBeforeUpload"
type="drag"
:action="api.imgManage"
class="uploadFile">
</Upload>
修改工具栏配置,当点击富文本时,调用相应的上传组件
handlers: {
'image': (value => {
if (value) {
document.querySelector('.uploadImage input').click()
}else {
this.quill.format('image', false);
}
}),
'upload': (value => {
if (value) {
document.querySelector('.uploadFile input').click()
}
})
}
这两个文件上传都要隐藏
.uploadImage,
.uploadFile{
width: 0;
height: 0;
display: none;
}
下面是插入文件的方法
<quill-editor
v-model="content"
:options="editorOption"
ref="QuillEditor">
</quill-editor>
methods: {
// 文件
handleFileSuccess (res, file) {
let fileNameLength = file.name.length
// 插入链接
let quill = this.$refs.QuillEditor.quill
let length = quill.getSelection().index;
quill.insertEmbed(length, 'link', {href:res, innerText:file.name}, "api")
quill.setSelection(length + fileNameLength)
},
}