使用富文本编辑器,上传图片。
首先要安装 quill-editor
npm install vue-quill-editor -S
引入到项目中,我是全局引入的
// 富文本编辑器
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
Vue.use(VueQuillEditor);
项目中使用
<el-upload
class="avatar-uploader"
:action="serverUrl" // 接口地址
name="file" // 参数名字
:headers="header" // 设置上传的请求头部。我的项目需要传token。
:show-file-list="false"
:on-success="uploadSuccess" // 成功的函数
:on-error="uploadError" // 错误的函数
:before-upload="beforeUpload"
>
</el-upload>
<quill-editor
v-model="editModel.content"
ref="myQuillEditor"
:options="editorOption"
@change="onEditorChange($event)"
@blur="editcontentRule"
>
</quill-editor>
const toolbarOptions = [
["bold", "italic", "underline", "strike"], // 加粗,斜体,下划线,删除线
["blockquote", "code-block"], //引用,代码块
[{ header: 1 }, { header: 2 }], // 几级标题
[{ list: "ordered" }, { list: "bullet" }], // 有序列表,无序列表
[{ script: "sub" }, { script: "super" }], // 下角标,上角标
[{ indent: "-1" }, { indent: "+1" }], // 缩进
[{ direction: "rtl" }], // 文字输入方向
[{ size: ["small", false, "large", "huge"] }], // 字体大小
[{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
[{ color: [] }, { background: [] }], // 颜色选择
[
{
font: [
"SimSun",
"SimHei",
"Microsoft-YaHei",
"KaiTi",
"FangSong",
"Arial",
],
},
], // 字体
[{ align: [] }], // 居中
["clean"], // 清除样式,
["link", "image"], // 上传图片、上传视频
];
// data中
serverUrl: “地址”, // 这里写你要上传的图片服务器地址
header: {
token: localStorage.token,
},
// 有的图片服务器要求请求头需要有token
// 富文本编辑器
quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画,刚开始是false,不显示
content: null,
editorOption: {
placeholder: "请在这里输入",
theme: "snow", //主题 snow/bubble
modules: {
history: {
delay: 1000,
maxStack: 50,
userOnly: false,
},
toolbar: {
container: toolbarOptions,
handlers: {
image: function (value) {
if (value) {
// 调用element的图片上传组件
document.querySelector(".avatar-uploader input").click();
} else {
this.quill.format("image", false);
}
},
},
},
},
},
uploadSuccess(res, file) {
// console.log(res)
// 获取富文本组件实例
let quill = this.$refs.myQuillEditor.quill;
// 如果上传成功
if (res) {
// 获取光标所在位置
let length = quill.getSelection().index;
// 插入图片,res为服务器返回的图片链接地址
quill.insertEmbed(length, "image", 这里是请求的数据结果的图片);
// 调整光标到最后
quill.setSelection(length + 1);
} else {
// 提示信息,需引入Message
this.$message.error("图片插入失败!");
}
this.quillUpdateImg = false;
},
// 富文本图片上传失败
uploadError(ee) {
console.log(ee);
// loading动画消失
this.quillUpdateImg = false;
this.$message.error("图片插入失败");
},
// 富文本图片上传前
beforeUpload(file) {
// 显示loading动画
this.quillUpdateImg = true;
},