<quill-editor ref="myQuillEditor" :options="editorOption"></quill-editor>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import {quillConfig} from "quill-config.js"; //自定义编辑器配置
export default {
data(){
return{
editorOption: quillConfig,
}
},
components: {
quillEditor
},
computed: {
editor() {
return this.$refs.myQuillEditor.quill;
}
},
}
/*富文本编辑图片上传配置*/
import axios from "axios";
import { md5 } from "../api/sign";
import { getJsPolicy } from "../api/api"; //oss后端签名
const uploadConfig = {
name: 'img', // 必填参数 文件的参数名
accept: 'image/png, image/gif, image/jpeg' // 可选 可上传的图片格式
};
// toolbar工具栏的工具选项(默认展示全部)
const toolbarOptions = [
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
["bold", "italic"],
["link", "image"]
];
const handlers = {
image: function image() {
var self = this;
var fileInput = this.container.querySelector('input.ql-image[type=file]');
if (fileInput === null) {
fileInput = document.createElement('input');
fileInput.setAttribute('type', 'file');
// 设置图片参数名
if (uploadConfig.name) {
fileInput.setAttribute('name', uploadConfig.name);
}
// 可设置上传图片的格式
fileInput.setAttribute('accept', uploadConfig.accept);
fileInput.classList.add('ql-image');
// 监听选择文件
fileInput.addEventListener('change', function () {
let pro = new Promise((resolve, rej) => {
// 判断签名有没有过期
var res = JSON.parse(localStorage.getItem("sign"));
var timestamp = Date.parse(new Date()) / 1000;
if (res && res.expire - 3 > timestamp) {
resolve(res);
} else {
getJsPolicy().then(res => {
if (res.code == 200) {
localStorage.setItem("sign", JSON.stringify(res.data));
resolve(res.data);
}
});
}
});
pro.then(success => {
var data = success;
var ossData = new FormData();
let file = fileInput.files[0];
ossData.append("name", file.name);
//key就代表文件层级和阿里云上的文件名
let imgType = file.type.split("/")[1];
let filename = file.name + file.size;
let keyValue = data.dir + "/" + md5(filename) + "." + imgType;
ossData.append("key", keyValue);
ossData.append("policy", data.policy);
ossData.append("OSSAccessKeyId", data.accessid);
ossData.append("success_action_status", 201);
ossData.append("signature", data.signature);
ossData.append("file", file, file.name);
axios.post(data.host, ossData, {
headers: {
"Content-Type": "multipart/form-data"
}
}).then(res=>{
if(res.status==201){
let url = data.host+'/'+keyValue;
let length = self.quill.getSelection(true).index;
//图片上传成功后,img的src需要在这里添加
self.quill.insertEmbed(length, 'image', url);
self.quill.setSelection(length + 1)
}
fileInput.value = ''
}).catch(err=>{
})
})
});
this.container.appendChild(fileInput);
}
fileInput.click();
}
};
export default {
placeholder: '请填写商品详情',
modules: {
toolbar: {
container: toolbarOptions, // 工具栏选项
handlers: handlers // 事件重写
}
}
};