实战向 如何在vue中使用富文本编辑器
富文本编辑器,其实网上已经有很多很多的攻略了,这也是一个经常会使用的东西,但是总有些人会觉得别人写的自己看不懂,所以今天我整点能复制过去直接就能用的
一、依赖插件
vue-quill-editor
这是核心插件直接安装之后引入就是了,基础好的建议直接去官网看api,比我这里更能找到自己想要的东西
二、上代码
1、引用插件
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
2、注册组件
components: { quillEditor },
3、需要的地方放入组件
<div>
<el-upload
style="display:none"
:action="uploadURL + '/tool/Upload/UploadImages'"
:show-file-list="false"
:on-success="drugAvatarSuccess"
:before-upload="beforeAvatarUpload"
accept=".jpg, .jpeg, .png, .JPG, .JPEG, .bmp"
:on-error="handleAvatarError"
id="uploadImg"
ref="uploadImg"
>
</el-upload>
//这里是结合elemen UI进行图片上传,保存图片地址至服务器,
//而不是将图片流存入服务器,节省空间
<quill-editor
v-model="changeHosform.details"
ref="myQuillEditor"
:options="editorOption"
@blur="onEditorBlur($event)"
@focus="onEditorFocus($event)"
@change="onEditorChange($event)"
>
</quill-editor>
</div>
4、声明变量
data(){
return{
uploadURL: "",
changeHosform: {
details: ""
},
},
editorOption: {
placeholder: "请在这里输入", //默认显示文字
modules: {
toolbar: {
container: [ //头部组件使用工具
[{ header: 1 }], // 标题,键值对的形式;1、2表示字体大小
["bold", "italic", "underline", "strike"], //加粗,斜体,下划线,删除线
["blockquote"], //引用,代码块
[{ list: "ordered" }, { list: "bullet" }], //列表
[{ direction: "rtl" }], // 文本方向
[{ size: ["small", "large", "huge"] }], // 字体大小
[{ header: [1, 2, 3, 4, 5, 6] }], //几级标题
[{ align: [] }], //对齐方式
["image"] //上传图片、上传视频
],
handlers: {
image: function(value) {
if (value) {
// 调用iview图片上传,改为element图片上传方法
document.querySelector("#uploadImg .el-upload").click();
} else {
this.quill.format("image", false);
}
}
}
}
}
}
}
正常情况下,上面的工具完全够用,如果还需要其他的,请前往官方文档查看
https://quilljs.com/docs/modules/toolbar/
5、编写方法
methods:{
//图片上传成功之后的回调
handleAvatarSuccess(res, file) {
let resp = res;
console.log(resp);
if (resp.code === 200) {
this.changeHosform.imageUrl = resp.data[0].filePath;
console.log(this.changeHosform);
} else {
this.$message.error(resp.message);
}
},
//富文本框图片上传成功回调
drugAvatarSuccess(res, file) {
// 获取富文本组件实例
let quill = this.$refs.myQuillEditor.quill;
// 如果上传成功
if (res) {
// 获取光标所在位置
let length = quill.getSelection().index;
// 插入图片,res为服务器返回的图片链接地址
quill.insertEmbed(length, "image", res.data[0].filePath);
// 调整光标到最后
quill.setSelection(length + 1);
} else {
// 提示信息,需引入Message
this.$message.error("图片插入失败");
}
},
//图片上传失败回调
handleAvatarError(err, file, fileList) {
// console.log(err, file, fileList);
this.$message.error("图片上传失败,请重新选择!!!");
},
//判断是否是图片
isImage(fileName) {
if (typeof fileName !== "string") return;
let name = fileName.toLowerCase();
return (
name.endsWith(".png") ||
name.endsWith(".jpeg") ||
name.endsWith(".jpg") ||
name.endsWith(".bmp") ||
name.endsWith(".PNG") ||
name.endsWith(".JPEG") ||
name.endsWith(".JPG") ||
name.endsWith(".BMP")
);
},
onEditorBlur() {}, // 失去焦点事件
onEditorFocus() {}, // 获得焦点事件
onEditorChange() {}, // 内容改变事件
}
6、上传数据
这个就不用写了吧,就是调用接口把数据上传而已
三、完成效果图展示
有帮助的话希望给个点赞,有问题的请留言评论,谢谢