×

VUE开发插件:vue-quill-editor

作者:andy0012021.02.07来源:Web前端之家浏览:5358评论:0
关键词:jsvue-quill-editor

了解下VUE开发插件:vue-quill-editor。用于编辑器的使用。

首先我们下载安装vue-quill-editor

npm install vue-quill-editor --save 或者 yarn add vue-quill-editor

下载好vue-quill-editor后,我们需要定义一个全局组件,把这个组件名字命名为quill-editor。

<div>
 <quill-editor
 v-model="value"
 ref="myQuillEditor"
 :options="editorOption"
 @change="onEditorChange"
 >
 </quill-editor>
 <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleChange" />
</div>

定义富文本选项配置

editorOption: {
 toolbar: [
 ['bold', 'italic', 'underline'], //加粗、斜体、下划线、删除线, 'strike'
 ['blockquote', 'code-block'], //引用、代码块
 [{ 'header': 1 }, { 'header': 2 }], //H1 H2
 [{ '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] }], //选中的文字容器高度
 [{ 'font': [] }], //字体样式
 [{ 'color': [] }, { 'background': [] }], //颜色、背景颜色
 [{ 'align': [] }], //对齐方式
 ['clean'], //清除选中文字的所有样式
 ['link', 'image', 'video'] //超链接、图片、视频链接
 ],
}

相关方法

改变原有富文本编辑器上传图片绑定方法

mounted() {
 if (this.$refs.myQuillEditor) {
 //myQuillEditor改成自己的
 this.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", this.imgHandler);
 }
},
methods:{
 imgHandler(state) {
 if (state) {
        //触发input的单击 ,fileBtn换成自己的
  this.$refs.fileBtn.click()
 }
 }
}

上传事件

handleChange(e) {
 const files = Array.prototype.slice.call(e.target.files);
 if (!files) {
 return;
 }
 let formdata = new FormData();
 formdata.append("file_name", files[0].name);
 formdata.append("imgs", files[0]);
 //使用了axios请求
 this.axios({
 url: this.$store.state.baseUrl + 'upload/ueditorFile',
 method: 'post',
 data: formdata,
 headers: {'client-identity': localStorage.getItem('session_id')}
 }).then((res) => {
 	//这里设置为空是为了联系上传同张图可以触发change事件
 this.$refs.fileBtn.value = "";
 if (res.data.code == 200) {
  let selection = this.$refs.myQuillEditor.quill.getSelection();
  //这里就是返回的图片地址,如果接口返回的不是可以访问的地址,要自己拼接
  let imgUrl = this.$store.state.baseUrl + res.data.data; 
  imgUrl = imgUrl.replace(/\\/g,"/") 
			//获取quill的光标,插入图片 
  this.$refs.myQuillEditor.quill.insertEmbed(selection != null ? selection.index : 0, 'image', imgUrl)   
			//插入完成后,光标往后移动一位 
  this.$refs.myQuillEditor.quill.setSelection(selection.index + 1);
 } 
 })
}

最后在父组件使用这个全局quill组件,并传递自己需要的相关参数,就完成啦~

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/vuejs20210207a2.html

网友评论文明上网理性发言 已有0人参与

发表评论: